2015-10-13 82 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; 

如果没有匹配,则不会返回任何行。