我正在运行此查询,该查询从一个表中选择一些字段并从其他一些表中返回计数。
我的问题:如果我的一个计数器字段为零,它不返回数字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中得到零,所以我可以通过计数来命令。
任何建议都是不可思议的。
答案 0 :(得分: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
答案 1 :(得分:1)
变化:
COUNT(comment_id)
到
IFNULL(COUNT(comment_id), 0)
答案 2 :(得分:1)
其他方式可能是:
coalesce(count(comment_id),0)
答案 3 :(得分: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
答案 4 :(得分:-2)
你能使用ISNULL吗?
ISNULL(com.cnt, 0) as comments