所以我有这种关系 国家(名称,代码,资本,邓贤兰,面积,人口)
我想找出人口第二多的国家。
到目前为止,我有这个;
select name, population
from
(select distinct name, population from country order by population desc limit 2) as A
order by population asc limit 1;
我只获得人口第二大的国家。我的问题是从这里开始,我很想在括号中与asc联系并收集两个结果,至少这是我能解决这个问题的唯一解决方案。我该怎么办?有更简单的方法吗?
答案 0 :(得分:1)
要获得人口第二大的国家/地区,请使用带有偏移量的limit
:
select name, population
from country c
order by population asc
limit 1 offset 1;
要获得第二个最少填充,请将asc
更改为desc
。您可以使用union all
:
(select name, population
from country c
order by population asc
limit 1 offset 1
) union all
(select name, population
from country c
order by population desc
limit 1 offset 1
)
请注意,如果您只有三个国家/地区,那么这仍将返回两行 - 同一国家/地区重复。如果要删除重复项,可以将union all
更改为union
。
答案 1 :(得分:0)
尝试:
请注意,如果有任何国家/地区存在平局,这将为您提供2行以上,而限制行将会切断关系。
select name, population, '2nd highest' as which
from country
where population =
(select max(population)
from country
where population < (select max(population) from country))
union all
select name, population, '2nd lowest' as which
from country
where population =
(select min(population)
from country
where population > (select min(population) from country))