[英]MySQL - Query with LEFT JOIN and group by not returning rows for count 0
I am running below mentioned query. 我正在下面提到的查询运行。
select c.id, c.code, c.name, count(a.iso_country) from countries c
left join airports a on c.code = a.iso_country group by a.iso_country
order by count(a.iso_country);
In my 'countries' table, I have 247 rows. 在“国家/地区”表中,我有247行。 In 'airports' table, 'iso_country' column maps to 'code' column in 'countries' table.
在“机场”表中,“ iso_country”列映射到“国家”表中的“代码”列。
Below are the table definitions. 以下是表定义。 Countries table -
国家表-
CREATE TABLE `countries` (
`id` int(11) NOT NULL,
`code` varchar(2) NOT NULL,
`name` text,
`continent` text,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`),
KEY `code_idx` (`code`)
)
Airports table - 机场表-
CREATE TABLE `airports` (
`id` int(11) NOT NULL,
`type` text,
`name` text,
`continent` text,
`iso_country` varchar(2) DEFAULT NULL,
`iso_region` text,
PRIMARY KEY (`id`),
KEY `country_iso_code_fk_idx` (`iso_country`),
CONSTRAINT `country_fk` FOREIGN KEY (`iso_country`) REFERENCES `countries`
(`code`) )
The issue I'm facing is - the query I mentioned above returns 242 countries - 241 countries with airports and 1 with null values for 'airports', but doesn't include other 5 countries who also don't have any airports. 我面临的问题是-我上面提到的查询返回242个国家-241个有机场的国家和1个“机场”值为空的国家,但不包括其他5个也没有机场的国家。 Please guide me what am I doing wrong in this query.
请指导我我在此查询中做错了什么。
PS:- I am just a novice in SQL. PS:我只是SQL的新手。
I'm running on MySQL 5.7 Community Edition. 我在MySQL 5.7 Community Edition上运行。 Thanks in advance.
提前致谢。
You want a count of airports by country, including those where there are none, right? 您想按国家/地区来计算机场,包括没有机场的机场,对吗?
Try this: 尝试这个:
SELECT
c.id, c.code, c.name, count(a.iso_country) AS airport_count
FROM
countries c LEFT JOIN airports a ON c.code = a.iso_country
GROUP BY
c.id, c.code, c.name
ORDER BY
airport_count DESC;
Could it have something to do with NULL values? 可能与NULL值有关吗? Your
a.iso_country
column is DEFAULT NULL
and c.code
is NOT NULL
. 您的
a.iso_country
DEFAULT NULL
而c.code
为NOT NULL
。 Usually when comparing values, if either can be NULL
, you want to use something like COALESCE
to provide a second option in the case that the value is NULL
. 通常在比较值时,如果其中一个可以为
NULL
,则在值为NULL
的情况下,您想使用类似COALESCE
方法提供第二个选项。 The reason for this being that NULL != ''
and NULL != 0
. 原因是
NULL != ''
和NULL != 0
。 What if you join on COALESCE(a.iso_country, '') = COALESCE(c.code, '')
? 如果您加入
COALESCE(a.iso_country, '') = COALESCE(c.code, '')
怎么办?
I'm also not sure how COUNT
behaves when given a NULL
. 我也不确定给定
NULL
时COUNT
行为。 You may need to be careful there. 您可能需要在这里小心。
您可以在where子句中检查这种情况吗?在没有找到Airport的表中隐式检查null。
where (airports.name.is null)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.