2014-12-31 27 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