MySQL、Oracle和SQL Server中Limit 语句的使用

发布时间 2023-08-23 15:12:02作者: 一纸荒年

MySQL中limit 的使用:

limit 关键字的作用

limit是限制的意思,用于 限制返回的查询结果的行数 (可以通过limit指定查询多少行数据)

limit 语法是 MySql的方言,用来完成分页

# 查询emp表中的前 5条数据
select * from emp limit 5;
# 查询emp表中 从第4条开始,查询6条
select * from emp limit 3,6;

 在SQL Server中,不支持 Limit 语句,但是它支持 TOP。

查询上述结果中前6条记录,则相应的SQL语句是:

select top 6 id from tablename

查询上述结果中第 7 条到第 9 条记录,则相应的SQL语句是:

select top 3 id from tablename
where id not in (
  select top 6 id from tablename
)
 
select top (n-m+1) id from tablename
where id not in (
  select top m-1 id from tablename
)
 
select top @pageSize id from tablename
where id not in (
  select top @offset id from tablename
)

oracle数据库不支持mysql中limit功能,但可以通过rownum来限制返回的结果集的行数,rownum并不是用户添加的字段,而是oracle系统自动添加的。

(1)使查询结果最多返回前10行:

select * from CLEAR where rownum<=10;

(2)使查询结果返回中间的10到100行:

select * from CLEAR where rownum<101 minus select * from CLEAR where rownum>9;

或者:

select * from (select t.*,rownum rn from CLEAR_01 t) nn where nn.rn>9 and nn.rn<101;

注:select * from CLEAR rownum>99 and rownum<101是错误的,oracle会认为条件不成立