Mysql

即使計數為空也顯示所有行

  • April 23, 2020

我想查看一個表中的所有行,然後對第二個表進行計數以查看有多少匹配項,但即使第二個表中有 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

試試看 !!!

引用自:https://dba.stackexchange.com/questions/265681