4

我正在运行这个查询,它从一个表中选择几个字段并从其他一些表中返回计数。

我的问题:如果我的计数器字段之一计数为零,它不会返回数字 0,它只是空白 - 这是我想尝试解决的问题。

SELECT mem.member_id, mem.screen_name, mem.firstname, mem.lastname, mem.country_code, 
mem.joined, rep.rep as reputation, com.cnt as comments FROM members AS mem
LEFT OUTER JOIN (
    SELECT member_id, SUM(awarded_what) as rep
    FROM members_reputation
    GROUP BY member_id) rep
    ON mem.member_id = rep.member_id
LEFT OUTER JOIN (
    SELECT member_id, COUNT(comment_id) as cnt
    FROM blog_comments
    GROUP BY comment_id) com
    ON mem.member_id = com.member_id
GROUP BY mem.member_id
ORDER BY mem.joined DESC

我想要的是这样的:

Screen Name      | Comments
-----------------|--------------------
marty76          | 0
jonnyBoy12       | 0
adamApple        | 12

但是,我得到的是这样的东西!

Screen Name      | Comments
-----------------|--------------------
marty76          | 
jonnyBoy12       | 
adamApple        | 12

使用我的服务器端语言,这很容易解决,方法是用零替换空值。但我希望零直接来自 SQL,这样我就可以按计数排序。

任何建议都会很棒。

4

5 回答 5

4

试试IFNULL函数

SELECT mem.member_id, mem.screen_name, mem.firstname, mem.lastname, mem.country_code,  
mem.joined, rep.rep as reputation, IFNULL(com.cnt,0) as comments FROM members AS mem 
LEFT OUTER JOIN ( 
    SELECT member_id, SUM(awarded_what) as rep 
    FROM members_reputation 
    GROUP BY member_id) rep 
    ON mem.member_id = rep.member_id 
LEFT OUTER JOIN ( 
    SELECT member_id, COUNT(comment_id) as cnt 
    FROM blog_comments 
    GROUP BY comment_id) com 
    ON mem.member_id = com.member_id 
GROUP BY mem.member_id 
ORDER BY mem.joined DESC 
于 2012-04-04T14:16:18.577 回答
1

改变:

COUNT(comment_id)

IFNULL(COUNT(comment_id), 0)
于 2012-04-04T14:16:37.053 回答
1

其他方式可能是:

 coalesce(count(comment_id),0)
于 2012-04-04T14:28:25.077 回答
1

我认为这应该给你你想要得到的结果,它比你的查询简单得多:

SELECT mem.member_id, mem.screen_name, mem.firstname, mem.lastname,
  mem.country_code, mem.joined,
  SUM(awarded_what) reputation, COUNT(comment_id) comments
FROM members mem
LEFT JOIN members_reputation rep ON mem.member_id = rep.member_id
LEFT JOIN blog_comments com ON mem.member_id = com.member_id
GROUP BY mem.member_id
ORDER BY mem.joined DESC
于 2012-04-04T14:29:08.463 回答
-2

你可以使用 ISNULL 吗?

ISNULL(com.cnt, 0) as comments
于 2012-04-04T14:16:21.650 回答