我的查询计算了一个月内带有特定标记的帖子数量,但显然我的WHERE
如果没有帖子则不会返回任何内容。问题是,我在图表上覆盖了另一个显示所有帖子的查询,而不仅仅是满足这些WHERE
条件的帖子。第二个查询通常会每个月都有一个结果。如果结果为null,如何让此查询返回零?我在这里已经阅读了一些答案,但无法弄明白。
SELECT MONTHNAME(post_time) AS month,
COALESCE(Count(distinct p.post_id), 0) AS count
FROM post.p
INNER JOIN post_tag_map t ON ( p.post_id = t.knote_id )
WHERE t.post_id IN (23,24,49,54)
/*these numbers are actually a variable, this is just an example*/
AND p.post_time >= (CURDATE() - INTERVAL 1 YEAR)
我试图从数据库开始时间显示月份和帖子。
答案 0 :(得分:4)
使用LEFT JOIN
包含不匹配的行:
SELECT MONTHNAME(post_time) AS month,
COALESCE(COUNT(distinct t.knote_id), 0) AS count
FROM post AS p
LEFT JOIN post_tag_map AS t
ON p.post_id = t.knote_id AND t.post_id IN (23,24,49,54)
WHERE p.post_time >= (CURDATE() - INTERVAL 1 YEAR)
GROUP BY month
请注意,在使用t
时,您必须将ON
条件放在WHERE
子句中,而不是LEFT JOIN
;否则,他们会在不匹配的行上失败。并且您必须从t
计算列,因此它将跳过不匹配行的空值。
答案 1 :(得分:0)
尝试使用ISNULL(金额,0)功能:
SELECT MONTHNAME(post_time) AS month,
ISNULL(Count(distinct p.post_id), 0) AS count
FROM post.p
INNER JOIN post_tag_map t ON ( p.post_id = t.knote_id )
WHERE t.post_id IN (23,24,49,54)
/*these numbers are actually a variable, this is just an example*/
AND p.post_time >= (CURDATE() - INTERVAL 1 YEAR)