[英]LEFT JOIN returns 1st row from left table only if right table is empty
I have two tables with following structure. 我有两个具有以下结构的表。
CREATE TABLE `countries` (
`id` BIGINT UNSIGNED AUTO_INCREMENT,
`title` VARCHAR (128) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE = InnoDB;
CREATE TABLE `cities` (
`id` BIGINT UNSIGNED AUTO_INCREMENT,
`country_id` BIGINT UNSIGNED NOT NULL,
`title` VARCHAR (128) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`country_id`) REFERENCES `countries` (`id`) ON DELETE CASCADE
) ENGINE = InnoDB;
Then I add 3 rows to the countries table: 然后将3行添加到国家表:
INSERT INTO `countries` VALUES
(DEFAULT, 'India'),
(DEFAULT, 'Pakistan'),
(DEFAULT, 'Afghanistan');
Now, when I run the following query: 现在,当我运行以下查询时:
SELECT c.title, COUNT(c2.id) AS cities
FROM countries AS c
LEFT JOIN cities AS c2
ON c2.country_id = c.id
GROUP BY c2.country_id;
I get: 我得到:
++++++++++++++++++++++++
| title | cities |
++++++++++++++++++++++++
| India | 0 |
++++++++++++++++++++++++
What I expect is: 我期望的是:
++++++++++++++++++++++++
| title | cities |
++++++++++++++++++++++++
| India | 0 |
| Pakistan | 0 |
| Afghanistan | 0 |
++++++++++++++++++++++++
I do not know why the query is returning only 1 row from the left table. 我不知道为什么查询只返回左表中的1行。 Can anybody please help? 有人可以帮忙吗?
Since you want result for all the entries of countries
table irrespective of whether the corresponding records in cities
table exist or not then LEFT JOIN
is the right choice. 由于无论cities
表中的对应记录是否存在,都需要countries
表所有条目的结果,因此LEFT JOIN
是正确的选择。
For some countries corresponding entries in cities
table might not exist. 对于某些国家/地区, cities
表中的相应条目可能不存在。 In this case you will get NULL
for those. 在这种情况下,您将获得NULL
。
Since no entries exist in cities
table you will get NULL
for c2.country_id
for all the rows of countries
table. 由于没有条目存在cities
表,你会得到NULL
的c2.country_id
为所有行countries
表。
Here NULL
represents your group. NULL
代表您的组。
If there were anything other than null then you would get more than 1 row. 如果除null之外还有其他任何内容,那么您将获得超过1行。 But in your case you are grouping by NULL
. 但是在您的情况下,您将按NULL
分组。
Look, c.id
isn't null in those cases and if you would group by c.id
then there would be three distinct ids in your sample input. 看,在这些情况下c.id
不为null,如果您按c.id
分组,则示例输入中将有三个不同的ID。 So, you would get three rows in your result set. 因此,您的结果集中将获得三行。
SELECT c.title, COUNT(c2.id) AS cities
FROM countries AS c
LEFT JOIN cities AS c2
ON c2.country_id = c.id
GROUP BY c.id;
More: 更多:
Some subtleties regarding COUNT
: 关于COUNT
一些技巧:
SELECT COUNT(0); Result: 1
SELECT COUNT(-1); Result: 1
SELECT COUNT(NULL); Result: 0
SELECT COUNT(71); Result: 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.