我有以下查询
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 中实现这个目标吗?
答案 0 :(得分:2)
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
,即使这样,它也经常令人困惑和难以阅读。