2015-05-14 44 views
11

我已经开始学习MySQL了。MySQL - 选择按字母顺序排列的名字

下面是表world

+-------------+-----------+---------+ 
| name  | continent | area | 
+-------------+-----------+---------+ 
| Afghanistan | Asia  | 652230 | 
| Albania  | Europe | 2831741 | 
| Algeria  | Africa | 28748 | 
| ...   | ...  | ...  | 
+-------------+-----------+---------+ 

我需要:

每个大洲和国家的自带首字母顺序排列

SELECT的结果必须名单成为:

+---------------+---------------------+ 
| continent |   name  | 
+---------------+---------------------+ 
| Africa  | Algeria    | 
| Asia   | Afghanistan   | 
| Caribbean  | Antigua and Barbuda | 
| Eurasia  | Armenia    | 
| Europe  | Albania    | 
| North America | Belize    | 
| Oceania  | Australia   | 
| South America | Argentina   | 
+---------------+---------------------+ 

回答

20

这是一个简单aggegation:

SELECT continent, MIN(name) AS name 
FROM world 
GROUP BY continent 
ORDER by continent 
+0

这也是正确的答案! – Dylan

+0

,比我的简单:) – Parado

+0

你不需要ORDER BY语句。 – unlucy7735

6

试试这个

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 
+1

这是问题的正确答案! – Dylan

-3

试试这个

SELECT continent, name FROM world ORDER BY name ASC; 
+1

这将列出世界上每一个国家。 –

-3

如果你需要列出每个大洲按字母顺序,你必须使用

 SELECT * from world ORDER by continent 

但是,如果你NEDD列表中的每个国家的有使用

 SELECT * from world ORDER by name 
+1

这将列出世界上每一个国家。 –

+0

不,这是要列出的国家或在bd continet,没有指定任何限制 –

11

如果是从SQLZoo练习,比IMO就应该是这个样子:

select continent, name from world x 
where name = (select name 
        from world y 
        where x.continent = y.continent 
        order by name asc 
        limit 1) 

附:我从那里学习SQL,这篇文章帮助了我。感谢@Parado!)

更新:我找到了site的答案。如果堆栈很有用。

+0

谢谢。 ...................... –

+0

为什么'select top 1'在内部select中不起作用? –

-2
select continent, name from world group by continent order by name 
+0

这不会为已选答案添加任何内容,但它不会回答问题:只会按OP的结果排序,而每个洲只有一个。 – Seki

1

的SqlZoo解决方案将能更好地看起来像这样:

SELECT continent, name FROM world x 
WHERE name <= ALL 
    (SELECT name FROM world y WHERE y.continent=x.continent) 
0

你看这个SQL:

select distinct continent, 
     (select name 
     from world y where y.continent = x.continent limit 1) as name 
from world x 
1
SELECT distinct x.continent , x.name 
FROM world x ,world y 
WHERE x.name = (SELECT y.name FROM world y 
WHERE y.continent=x.continent order by y.name asc limit 1) ; 
0
SELECT continent, 
     name 
FROM world x 
WHERE name= 
    (SELECT name 
    FROM world y 
    WHERE x.continent=y.continent 
    ORDER BY name 
    LIMIT 1) 

这是关联/同步查询。