2015-05-14 73 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) 

這是關聯/同步查詢。