使用mysql group by返回0

时间:2010-08-30 02:53:52

标签: sql mysql count group-by

像这样的数据库表

============================
= suburb_id   |   value
= 1           |    2
= 1           |    3
= 2           |    4
= 3           |    5

查询是

SELECT COUNT(suburb_id) AS total, suburb_id 
  FROM suburbs 
 where suburb_id IN (1,2,3,4) 
GROUP BY suburb_id

但是,当我运行此查询时,当suburb_id = 0时,它不会给COUNT(suburb_id)= 0 因为在郊区表中,没有suburb_id 4,我希望此查询为suburb_id = 4返回0,如

============================
= total       |   suburb_id
= 2           |    1
= 1           |    2
= 1           |    3
= 0           |    4

4 个答案:

答案 0 :(得分:10)

GROUP BY需要使用行,因此如果某个类别没有行,则不会获得计数。可以将where子句视为在将源行组合在一起之前限制它们。 where子句未提供要分组的类别列表。

您可以做的是编写一个查询来选择类别(郊区),然后在子查询中进行计数。 (我不确定MySQL对此的支持是什么样的)

类似的东西:

SELECT 
  s.suburb_id,
  (select count(*) from suburb_data d where d.suburb_id = s.suburb_id) as total
FROM
  suburb_table s
WHERE
  s.suburb_id in (1,2,3,4)

(MSSQL,道歉)

答案 1 :(得分:4)

此:

SELECT  id, COUNT(suburb_id)
FROM    (
        SELECT  1 AS id
        UNION ALL
        SELECT  2 AS id
        UNION ALL
        SELECT  3 AS id
        UNION ALL
        SELECT  4 AS id
        ) ids
LEFT JOIN
        suburbs s
ON      s.suburb_id = ids.id
GROUP BY
        id

或者这个:

SELECT  id,
        (
        SELECT  COUNT(*)
        FROM    suburb
        WHERE   suburb_id = id
        )
FROM    (
        SELECT  1 AS id
        UNION ALL
        SELECT  2 AS id
        UNION ALL
        SELECT  3 AS id
        UNION ALL
        SELECT  4 AS id
        ) ids

本文比较了两种方法的表现:

,尽管在​​您的情况下并不重要,因为您只查询4条记录。

答案 2 :(得分:1)

查询:

select case
         when total is null then 0
         else total
       end as total_with_zeroes,
       suburb_id
from (SELECT COUNT(suburb_id) AS total, suburb_id 
        FROM suburbs 
       where suburb_id IN (1,2,3,4) 
    GROUP BY suburb_id) as dt

答案 3 :(得分:1)

如果所有条件都像这种情况一样简单,那么@ geofftnz的解决方案效果很好。但我只需要解决类似的问题来生成一个报告,其中报告中的每一列都是不同的查询。当您需要组合来自多个select语句的结果时,这样的事情可能会起作用。

您可能必须以编程方式创建此查询。使用左连接允许查询返回行,即使没有与给定id的suburb_id匹配也是如此。如果您的数据库支持它(大多数都支持),您可以使用IFNULL将null替换为0:

select IFNULL(a.count,0), IFNULL(b.count,0), IFNULL(c.count,0), IFNULL(d.count,0)
from (select count(suburb_id) as count from suburbs where id=1 group by suburb_id) a,
 left join (select count(suburb_id) as count from suburbs where id=2 group by suburb_id) b on a.suburb_id=b.suburb_id
 left join (select count(suburb_id) as count from suburbs where id=3 group by suburb_id) c on a.suburb_id=c.suburb_id
 left join (select count(suburb_id) as count from suburbs where id=4 group by suburb_id) d on a.suburb_id=d.suburb_id;

关于这一点的好处是(如果需要)每个"左连接"可以使用稍微不同(可能相当复杂)的查询。

免责声明:对于大型数据集,这种类型的查询可能效果不佳(我没有编写足够的sql知道而不进一步调查),但至少它应该给出有用的结果; - )