Mysql
即使計數為空也顯示所有行
我想查看一個表中的所有行,然後對第二個表進行計數以查看有多少匹配項,但即使第二個表中有 0 個匹配項,我也想全部查看。
我的查詢:
SELECT a.area_name, COUNT(b.id) AS cnt FROM areas a LEFT JOIN events b ON a.area_id = b.i_area WHERE YEAR(b.i_date) = YEAR(CURRENT_DATE()) AND MONTH(b.i_date) = MONTH(CURRENT_DATE()) GROUP BY a.area_name
範例所需的輸出:
area 1 | 1 area 2 | 0 area 3 | 5
我目前得到的是:
area 1 | 1 area 3 | 5
我也嘗試了 CROSS 和 RIGHT 加入,只是為了確保,但我沒有得到想要的效果。
我錯過了什麼或做錯了什麼?
你可以先這樣做:刪除
WHERE
子句SELECT a.area_name, COUNT(b.id) AS cnt FROM areas a LEFT JOIN events b ON a.area_id = b.i_area GROUP BY a.area_name
這將顯示
area 2
如果你真的想要這個
WHERE
子句,把它移到ON
子句中SELECT a.area_name, COUNT(b.id) AS cnt FROM areas a LEFT JOIN events b ON a.area_id = b.i_area AND YEAR(b.i_date) = YEAR(CURRENT_DATE()) AND MONTH(b.i_date) = MONTH(CURRENT_DATE()) GROUP BY a.area_name
試試看 !!!