2017-03-18 57 views
0

我希望一些幫助。我從來沒有寫過任何SQL搜索查詢,我不確定我是否在這裏建立基礎。這會解決以下問題嗎?感謝您的時間。如何獲得前n行

SELECT * FROM table ORDER BY population DESC limit 3;

下面是問題: 給定以下數據庫表,編寫一個SQL查詢,該查詢將返回具有最高種羣的三隻動物的動物名稱和食物。

|id |animal |food  |population | 
|---|----------|------------|-----------| 
|35 |ocelot |mouse  |1200000 | 
|36 |dingo  |rabbit  |16000000 | 
|41 |capybara |grass  |400000  | 
|52 |remora |blood  |82000000 | 
|54 |emu  |fruit  |725000  | 
|63 |gecko  |insects  |9000000 | 
|68 |earwig |lettuce  |420000000 | 
+0

的數據庫是你真正使用Oracle或MySQL? – GurV

回答

4

在Oracle 11g或之前,你可以在有序的結果使用rownum過濾器從子查詢:

select * 
from (
    Select * 
    From Your_table 
    Order by population desc 
) t where rownum <= 3; 

在Oracle 12c中+,你可以使用FETCH FIRST條款:

Select * 
From Your_table 
Order by population desc 
fetch first 3 rows only; 

在MySQL中,你可以使用LIMIT

Select * 
From Your_table 
Order by population desc 
limit 3; 

在S QL服務器,您可以使用TOP

Select top 3 * 
From Your_table 
Order by population desc; 
1
select 
    animal, 
    food 
from 
    table 
order by 
    population DESC 
top 3 

試試這個?

+0

您按升序排列,而不是降序排列。 'TOP 3'不是有效的MySQL,PL/SQL或T-SQL。 – Dai

+0

第一部分編輯感謝,並感謝您的幫助。 –

0

使用TOP方法,讓您的結果:

SELECT TOP 3 animal,food FROM table order by population DESC