2015-10-13 66 views
0

我有這樣的選擇:避免空計數的MySQL

select 'fv' prefix, c.user, MAX(f.data) as data, c.user, count(c.user) as logs 
from favorites f inner join 
    cadastro c 
    ON f.user = c.id 
where f.fv = '1' and c.user <> f.user and f.data > now() 

如果我沒有結果表明,MySQL的顯示了這個:

prefix - user - data - user - logs 
fv NULL NULL NULL 0 

我不想顯示的時候沒有結果。哪裏不對?是計數(c.user)?我如何避免計數爲0?

回答

2

無聚合查詢group by總是返回一行。一種簡單的方法是添加聚合:

select 'fv' as prefix, c.user, MAX(f.data) as data, c.user, count(c.user) as logs 
from favorites f inner join 
    cadastro c 
    ON f.user = c.id 
where f.fv = '1' and c.user <> f.user and f.data > now() 
group by f.fv; 

如果沒有匹配,則不會返回任何行。