如何从下表国家/地区列出表面积大于同一地区所有其他国家/地区的所有国家/地区的名称:
+----------------------------------------------+---------------------------+-------------+
| name | region | surfacearea |
+----------------------------------------------+---------------------------+-------------+
| Aruba | Caribbean | 193.00 |
| Afghanistan | Southern and Central Asia | 652090.00 |
| Angola | Central Africa | 1246700.00 |
| Anguilla | Caribbean | 96.00 |
| Albania | Southern Europe | 28748.00 |
| Andorra | Southern Europe | 468.00 |
| Netherlands Antilles | Caribbean | 800.00 |
到目前为止,我已经提供了此代码,但这并没有列出国家/地区?这段代码是否正确?
select region, max(surfacearea) as maxArea
from country
group by region;
答案 0 :(得分:2)
可以使用临时表的内连接
select name from
country as a
inner join
( select region, max(surfacearea) as maxarea
from country
group by region ) as t on a.region = t.region
where a.surfacearea = t.maxarea;
答案 1 :(得分:1)
看起来你的查询确定了最大的"每个区域的表面区域的价值。要获取国家/地区,您可以将查询结果再次加入国家/地区表格,以获取与地区和地区相匹配的国家/地区。
SELECT c.*
FROM ( -- largest surfacearea for each region
SELECT n.region
, MAX(n.surfacearea) AS max_area
FROM country n
GROUP BY n.region
) m
JOIN country c
ON c.region = m.region
AND c.surfacearea = m.max_area
答案 2 :(得分:1)
您可以在WHERE IN
转化中使用原始查询:
select *
from country
where (region, surfacearea) in (
select region, max(surfacearea) as maxArea
from country
group by region
)
其他方式:
select c1.*
from country c1
left join country c2
on c2.region = c1.region
and c2.surfacearea > c1.surfacearea
where c2.region is null;
select c1.*
from country c1
where not exists (
select *
from country c2
where c2.region = c1.region
and c2.surfacearea > c1.surfacearea
);