2017-04-17 75 views
0

我如何查詢我想要的輸出,像我這樣通過我的tbl_clinics.clinic_name進行分組。現在我的查詢發生了什麼?爲什麼它是,它並沒有顯示我的零個值,比如我想要的東西輸出這樣的:mysql query在查詢中顯示爲空

clinic name | total_check 
Clinic 1 | 4 
Clinic 2 | 0 
Clinic 3 | 0 
Clinic 4 | 0 

這裏是我的查詢:

SELECT 
tbl_clinics.clinic_name, 
COALESCE(COUNT(tbl_check_up.check_up_id),0) AS total_check 
FROM 
tbl_clinics 
LEFT OUTER JOIN tbl_check_up ON tbl_clinics.clinic_id = tbl_check_up.clinic_id 
WHERE tbl_clinics.user_id = "102" AND MONTH(tbl_check_up.check_up_date) = "02" 
GROUP BY tbl_clinics.clinic_name 

和我所得到的是隻喜歡這些:

clinic_name | total_check 
    Clinic 1  |  4 

爲什麼它不顯示我的其他診所? ..我怎麼操縱這些? 。請幫助我從我想要的內容中獲得正確的輸出,並向我解釋爲什麼我的輸出不能很好地完成我想要的輸出。

回答

1

WHERE子句將決定輸出哪些行。如果你想輸出表「tbl_clinics」內的所有記錄,試試這個:

SELECT tbl_clinics.clinic_name, 
     Count(tbl_check_up.check_up_id) AS total_check 
FROM tbl_clinics 
     LEFT JOIN tbl_check_up 
       ON tbl_clinics.clinic_id = tbl_check_up.clinic_id 
       AND tbl_clinics.user_id = "102" 
       AND Month(tbl_check_up.check_up_date) = "02" 
GROUP BY tbl_clinics.clinic_name 

而且,我認爲,COALESCE()在COUNT()是不必要的,因爲COUNT()將始終返回0,不爲空,當沒有行遇到。

0

你可以嘗試

SELECT tbl_clinics.clinic_name, 
     COALESCE(COUNT(tbl_check_up.check_up_id), 0) AS total_check 
FROM tbl_clinics 
     LEFT OUTER JOIN tbl_check_up 
        ON tbl_clinics.clinic_id = tbl_check_up.clinic_id 
WHERE tbl_clinics.user_id = "102" 
     AND (tbl_check_up.check_up_date IS NULL 
       OR MONTH(tbl_check_up.check_up_date) = "02") 
GROUP BY tbl_clinics.clinic_name