简体   繁体   English

MYSQL计数 - 如果为null则返回0

[英]MYSQL Count - Return 0 if null

Here's my query: 这是我的查询:

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;

Should look like this 应该是这样的

100 50
25  50
0   0
100 35

But if there is no count, it looks like this (missing) 但如果没有计数,它看起来像这样(缺少)

100 50
40  50
100 35

How can I fill in 0's instead? 我怎样才能填写0?

If you don't have a table with the uri stems in then something ugly like 如果你没有一个带有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

Should do it 应该这样做

Try this (untested): 试试这个(未经测试):

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM