从子查询中选择前 n 个
Selecting top n from subquery
假设我有一个 table world(continent, country)
.
如何过滤此 table 以仅包含每个大陆前五个国家/地区的 continent
和 country
(按字母顺序排列)?如果我只想 select 按字母顺序排列的第一个国家/地区,我只需这样做:
SELECT continent, country
FROM world x WHERE country = (
SELECT country
FROM world y
WHERE x.continent = y.continent
ORDER BY country asc
LIMIT 1
)
但是如果我尝试通过
获得多个国家/地区
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
)
然后抛出一个错误:
This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
我可以 运行 的替代查询是什么?
对于每一行,计算列表中它前面有多少个国家:
SELECT continent, country
FROM world x
WHERE 5 > (
SELECT count(*)
FROM world y
WHERE x.continent = y.continent
AND x.country > y.country
)
假设我有一个 table world(continent, country)
.
如何过滤此 table 以仅包含每个大陆前五个国家/地区的 continent
和 country
(按字母顺序排列)?如果我只想 select 按字母顺序排列的第一个国家/地区,我只需这样做:
SELECT continent, country
FROM world x WHERE country = (
SELECT country
FROM world y
WHERE x.continent = y.continent
ORDER BY country asc
LIMIT 1
)
但是如果我尝试通过
获得多个国家/地区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
)
然后抛出一个错误:
This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
我可以 运行 的替代查询是什么?
对于每一行,计算列表中它前面有多少个国家:
SELECT continent, country
FROM world x
WHERE 5 > (
SELECT count(*)
FROM world y
WHERE x.continent = y.continent
AND x.country > y.country
)