2014-04-19 46 views
1

我有一個查詢,計算一個月的帖子數量與某個標記,但顯然我的WHERE不會返回任何東西,如果沒有帖子。問題在於,我在圖表上覆蓋了顯示所有帖子的另一個查詢,而不僅僅是符合這些WHERE條件的查詢。第二個查詢通常每個月都會有一個結果。我如何得到這個查詢返回零,如果結果爲空?我已經閱讀了一些答案,但不能完全弄明白。獲取計數0而不是NULL MySQL查詢

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) 

我試圖顯示從數據庫的時間開始兩個月和帖子。

回答

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 

請注意,您在使用時LEFT JOINt條件ON條款,不WHERE,在;否則,他們會在不匹配的行上失敗。而且您必須從t開始對列進行計數,因此它將跳過非匹配行的空值。

DEMO

+0

這看起來正確的,但它仍然不是三月返回任何東西(0篇帖子共,所以對我來說很有意義,但不想要的結果)。 – dcclassics

+0

您需要加入一個包含月份的表格。請參閱http://stackoverflow.com/questions/23130805/extract-all-month-in-one-coulmn-from-date/23131017#23131017瞭解如何在運行中創建它。 – Barmar

+0

好的。同一張表包含月份。他們出現,如果我不做在哪裏。如果這是有道理的。 – dcclassics

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)