2014-12-31 29 views

回答

0

使用的列名,而不是别名

select 
    au.UserName as UsersName, 
    (
     select count(sg.Id) from sg 
     where sg.Username = au.UserName 
    ) as Count 
... 

DEMO http://sqlfiddle.com/#!3/8b62d/10

+0

为au.Username选择的值是否与在subselect语句外部选择的值相同? – PLan

+0

是的,它遍历au.UserName每行 – HaveNoDisplayName

+0

这工作,谢谢。把count()放在select中是什么。 – PLan

1

count()select

select au.UserName as UsersName, 
     (select count(sg.Id) 
     from sg 
     where sg.Username = au.UserName 
     ) 

的相关性也不能使用列别名。它需要使用as之前的部分。别名不在子查询的范围内。

+0

好描述 – HaveNoDisplayName

+0

这工作正是我想要的。谢谢 – PLan

0
select au.UserName as UsersName, count(sg.Id) 
    from au 
    join sg 
    on sg.Username = au.UserName 
group by au.UserName