如何获得前n行
我希望一些帮助。我从来没有写过任何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 |
在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;
select
animal,
food
from
table
order by
population DESC
top 3
试试这个?
您按升序排列,而不是降序排列。 'TOP 3'不是有效的MySQL,PL/SQL或T-SQL。 – Dai
第一部分编辑感谢,并感谢您的帮助。 –
使用TOP方法,让您的结果:
SELECT TOP 3 animal,food FROM table order by population DESC
的数据库是你真正使用Oracle或MySQL? – GurV