2016-12-01 410 views
0

我試圖從包含外表中的外觀計數的表中獲取結果。此表可以有0個或更多外觀。用LEFT JOIN和GROUP BY COUNT(*)在MySQL中包含NULL

像下面的例子:

表:顏色

+------+---------+ 
| id | name | 
+------+---------+ 
| 1 | red | 
| 2 | blue | 
| 3 | yellow | 
| 4 | green | 
+------+---------+ 

表:水果

+--------+----------+ 
| name | color_id | 
+--------+----------+ 
| apple | 1  | 
| banana | 3  | 
| grape | 4  | 
| lemon | 3  | 
+--------+----------+ 

所以我需要列出所有顏色,並在果表發生,返回像這樣:

1, red, 1 
2, blue, 0 
3, yellow, 2 
4, green, 1 

我試圖與此查詢:

SELECT `c`.`id`, `c`.`name`, COUNT(1) 
FROM color `c` 
LEFT JOIN fruit `f` 
ON `c`.`id` = `f`.`color_id` 
GROUP BY `c`.`id` 

此查詢爲「藍色」,而不是返回的計數。怎麼一回事,因爲顏色「藍色」沒有出現在果表

+1

不計(1)始終返回1? – Jerry

+1

那麼,你正在計算1的數量,而mysql會這麼做。用'count(f.name)'替換'count(1)',然後它會計算水果的數量。 – Solarflare

+0

@Jerry否,'COUNT(任何)'計數遇到的非空值的數量。 – Uueerdo

回答

4

這工作:

SELECT c.id, COUNT(f.name) 
FROM color c 
LEFT JOIN fruit f ON c.id = f.color_id 
GROUP BY c.id 

你要算水果的領域,使NULL可以返回,這變成了零。

1

你把計數(1),變化計數(f.color_id)

select 
    c.id 
    , c.name 
    , count(f.color_id) as [Color Count] 
from color as c 
    left join fruit as f 
    on c.id = f.color_id 
group by c.id, c.name