[英]Selecting top n from subquery
Suppose I have a table world(continent, country)
. 假设我有一个桌子
world(continent, country)
。
How can I filter this table to include just the continent
and country
of the first five countries in each continent (alphabetically)? 如何过滤此表以仅包括每个大陆的前五个国家的
continent
和country
(字母顺序)? If I want to select only the first country alphabetically, I simply do: 如果我只想按字母顺序选择第一个国家,则只需执行以下操作:
SELECT continent, country
FROM world x WHERE country = (
SELECT country
FROM world y
WHERE x.continent = y.continent
ORDER BY country asc
LIMIT 1
)
But if I try to get more than one country with 但是,如果我尝试超越一个国家
SELECT continent, country
FROM world x WHERE country in (
SELECT country
FROM world y
WHERE x.continent = y.continent
ORDER BY country asc
LIMIT 5
)
then an error is thrown: 然后抛出一个错误:
This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
What is an alternative query that I can run? 我可以运行的替代查询是什么?
For each row, count how many countries are before it on the list: 对于每一行,请计算列表中位于该行之前的国家/地区:
SELECT continent, country
FROM world x
WHERE 5 > (
SELECT count(*)
FROM world y
WHERE x.continent = y.continent
AND x.country > y.country
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.