2016-04-21 43 views
0

我有以下查詢SQL:輸出0時,計數()有沒有行

Select 
    count(project.id) as '# Projects', 
    c2.name as ' Country name' 
from 
    project, 
    country c2, 
    project_country 
where 
    project_country.project_id = project.id and 
    project_country.country_id= c2.id 
group by 
    c2.name; 

它返回只有當count()>0與某一特定國家的項目數量。

對於不具有關聯與我想在#Projects的值列中的任何項目的國家。有沒有什麼辦法可以實現這個mysql

回答

1

請閱讀SQL教程,其中包括JOIN s。

SELECT 
    C2.name AS `Country name`, 
    COUNT(P.id) AS `# Projects` 
FROM 
    Project P 
LEFT OUTER JOIN Project_Country PC ON PC.project_id = P.id 
LEFT OUTER JOIN Country C ON C.id = PC.country_id 
GROUP BY 
    C.name 

,你不能與你的查詢做的原因是因爲你使用的JOIN舊的風格。舊的,我的意思是大約在1994年。除非你的RDBMS包含特殊的語法(比如* =),否則它不允許使用OUTER JOIN,即使這樣它往往會令人困惑和難以閱讀。

2

您可以使用IFNULLCOALESCE

解決方案與IFNULL

Select 
    IFNULL(count(project.id),0) as '# Projects', 
    c2.name as ' Country name' 
from 
    project, 
    country c2, 
    project_country 
where 
    project_country.project_id = project.id and 
    project_country.country_id= c2.id 
group by 
    c2.name; 

解決方案與COALESCE

Select 
    COALESCE(count(project.id),0) as '# Projects', 
    c2.name as ' Country name' 
from 
    project, 
    country c2, 
    project_country 
where 
    project_country.project_id = project.id and 
    project_country.country_id= c2.id 
group by 
    c2.name; 
+0

感謝@sebastianbrosch,但它似乎並不爲國家顯示0,唐;噸有任何相關的項目 –