MySQL - 按字母顺序选择首先出现的名称

Dyl*_*lan 13 mysql sql

我已经开始学习MySQL了.

这是表格world:

+-------------+-----------+---------+
|    name     | continent |  area   |
+-------------+-----------+---------+
| Afghanistan | Asia      | 652230  |
| Albania     | Europe    | 2831741 |
| Algeria     | Africa    | 28748   |
| ...         | ...       | ...     |
+-------------+-----------+---------+
Run Code Online (Sandbox Code Playgroud)

我需要:

列出每个大洲以及按字母顺序排列的国家/地区名称

SELECT的结果必须是:

+---------------+---------------------+
|   continent   |         name        |
+---------------+---------------------+
| Africa        | Algeria             |
| Asia          | Afghanistan         |
| Caribbean     | Antigua and Barbuda |
| Eurasia       | Armenia             |
| Europe        | Albania             |
| North America | Belize              |
| Oceania       | Australia           |
| South America | Argentina           |
+---------------+---------------------+
Run Code Online (Sandbox Code Playgroud)

dno*_*eth 25

这是一个简单的aggegation:

SELECT continent, MIN(name) AS name
FROM world 
GROUP BY continent
ORDER by continent
Run Code Online (Sandbox Code Playgroud)

  • 您可能不需要它,但 OP 期望一个有序的结果集,即使结果当前以正确的顺序返回,它也可能随时更改。 (2认同)

Ole*_*uts 12

如果它是来自SQLZoo的练习,那么它应该看起来像这样:

select continent, name from world x
where name = (select name 
                  from world y 
                  where  x.continent =  y.continent 
                  order by name asc 
                  limit 1)
Run Code Online (Sandbox Code Playgroud)

PS我现在从那里学习SQL,这篇文章帮助了我.感谢@Parado!)

更新:我发现这个网站有答案.如果堆栈有用.


Rob*_*ert 7

试试这个

select distinct  w.continent, 
                 (select w2.name 
                  from world w2 
                  where  w.continent =  w2.continent 
                  order by name asc 
                  limit 1) name 
from world w
order by w.continent
Run Code Online (Sandbox Code Playgroud)