SQL:count()没有行时输出0

时间:2016-04-21 16:33:41

标签: mysql sql count

我有以下查询

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 列中获得 0 值。我有什么办法可以在 mysql 中实现这个目标吗?

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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,即使这样,它也经常令人困惑和难以阅读。