我获得了以下关系模式 -
country (countrycode,name,capital) &
population (populationcode,population,countrycode)
其中countrycode是外键w.r.t.关系国家。我必须使用最大人口来预测国家,但聚合操作MAX(population)
不能直接用于给定的命令 - 。
SELECT pcode, ccode, name, capital
FROM population NATURAL JOIN country
WHERE ((SELECT MAX(population) as maxpopulation FROM population NATURAL JOIN country))
给定的数据集 -
INSERT INTO country VALUES(1,'INDIA','NEW DELHI');
INSERT INTO country VALUES(2,'U.S.A.','WASHINGTON DC');
INSERT INTO country VALUES(3,'U.K.','LONDON');
INSERT INTO country VALUES(4,'CHINA','BEIJING');
INSERT INTO country VALUES(5,'JAPAN','TOKYO');
INSERT INTO population VALUES(1,1200000000,1);
INSERT INTO population VALUES(2,350000000,2);
INSERT INTO population VALUES(3,65640000,3);
INSERT INTO population VALUES(4,1300000000,4);
INSERT INTO population VALUES(5,127000000,5);
因为它在终端中产生以下输出 -
+-------+-------+--------+---------------+
| pcode | ccode | name | capital |
+-------+-------+--------+---------------+
| 1 | 1 | INDIA | NEW DELHI |
| 2 | 2 | U.S.A. | WASHINGTON DC |
| 3 | 3 | U.K. | LONDON |
| 4 | 4 | CHINA | BEIJING |
| 5 | 5 | JAPAN | TOKYO |
+-------+-------+--------+---------------+
5 rows in set (0.00 sec)
预期的输出是 -
+-------+-------+--------+---------------+
| pcode | ccode | name | capital |
+-------+-------+--------+---------------+
| 4 | 4 | CHINA | BEIJING |
+-------+-------+--------+---------------+
1 rows in set (0.00 sec)
但它应该只告诉人口最多的国家属性是中国。
那么可以进行什么样的操作?
答案 0 :(得分:1)
简单如下:
SELECT pcode, ccode, name, capital
FROM population NATURAL JOIN country
WHERE population = (SELECT MAX(population) FROM population)
答案 1 :(得分:1)
请勿使用NATURAL JOIN
。这是一种憎恶,因为它使用具有相同名称的键。它甚至不使用正确声明的外键关系。
如果您只想查找一行,那么我建议您ORDER BY
和LIMIT
:
select p.populationcode, p.countrycode, c.name, c.capital
from population p join
country c
using (countrycode) -- of course, the traditional explicit "on" is totally correct too
order by p.population desc
limit 1;
当您使用比较最大人口的版本时,您可以获得重复项。如果这是你想要的,那么一定要使用那个版本。
答案 2 :(得分:0)
在WHERE
中使用子查询并使用LIMIT
功能。
SELECT p.populationcode, c.countrycode, c.name, c.capital
FROM population p
INNER JOIN country c ON p.countrycode = c.countrycode
WHERE (SELECT countrycode
FROM (SELECT countrycode, population
FROM population
ORDER BY population DESC LIMIT 1)) = c.countrycode