2012-11-12 131 views
0

这里是我的查询:MYSQL计数 - 返回0,如果空

select COUNT(*) as total, COUNT(distinct user) as unique 
FROM table 
WHERE uristem in ('/example/', '/example/', '/example/', '/example/') 
     and time > DATE_SUB(NOW(), INTERVAL 24 HOUR)' 
group by uristem; 

应该是这样的

100 50 
25 50 
0 0 
100 35 

但是,如果没有计数,它看起来像这样(失踪)

100 50 
40 50 
100 35 

我该如何填写0代替?

+3

添加一些例子请记录。 –

回答

1

如果你没有一个表的URI中那么丑的东西像

Select 
    u.uristem, 
    count(t.uristem), 
    count(distinct t.user) as unique 
From (
    Select '/example1/' As uristem 
    Union All Select '/example2/' 
    Union All Select '/example3/' 
    Union All Select '/example4/' 
) u 
    Left Outer Join 
    table t 
    On u.uristem = t.uristem And 
    t.time > Date_Sub(Now(), Interval 24 Hour) 
Group By 
    u.uristem 

应该这样做

+1

嗨@Laurence,我的答案与你大致相同,但后来才意识到 - 有一个t的条件打破了外连接的好处。 – JohnLBevan

+0

@JohnLBevan哦,只要把它移到部分条件就可以解决这个问题,欢呼! – Laurence

+0

不用担心 - 比我的子查询解决方法更清洁 - 很好 – JohnLBevan

1

试试这个(未经测试):

select COUNT(t.uristem) as total 
, COUNT(distinct t.user) as unique 
FROM 
    (
     select uristem, user 
     from table 
     where time > DATE_SUB(NOW(), INTERVAL 24 HOUR) 
    ) t 
right outer join 
(
    select '/example/' x 
    union select '/example/' 
    union select '/example/' 
    union select '/example/' 
) y 
on t.uristem = y.x 
group by y.x;