sql 查询行数限制

DB2 用: fetch first 100 rows only
eg:select * from Schema.Table_name fetch first 100 rows only; -- 检索前100行

Mysql 用:LIMIT limit 可以有1个或2个参数,参数为整数常量;如果是两个参数,第一个参数指定返回记录行的偏移量,第二个参数指定返回记录行的最大数目。
eg:select * from Table_name limit 5,10; -- 检索 6至15行
若一个参数,它表示返回最大的记录行数目:select * from Table_name limit 5; --检索前5个记录行 limit 5 相当于 limit 0,5
检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1:select * from Table_name limit 5,-1; -- 检索 6至last 行

SQL Server 用 :select top语句进行分页
eg: select top 10 * from Table_name where id not in (select top 20 id from Table_name order by id) order by id

Oracle 用:rownum

  • rownum是oracle 顺序分配为 查询返回的行的编号,返回的第一行分配的是1,第二行是2,依此类推,这个伪字段可以用于限制查询返回的总行数,但rownum不能以任何表的名称作为前缀。
    eg:select rownum,id,name from Table where rownum=1 --查询第一条记录
  • 如果想查询从第二行记录以后的记录,使用rownum>2是查不出记录的,原因是由于rownum是一个总是从1开始的伪列,Oracle 认为rownum> n(n>1的自然数)这种条件依旧不成立,所以查不到记录。
  • 查询第二行后面的记录可使用子查询方法来解决(子查询中的rownum必须要有别名,否则还是查不出记录来,因为rownum不是某个表的列,如果不起别名的话,无法知道rownum是子查询的列还是主查询的列)。
    eg:select * from (select rownum cnt ,id,name from Table) where cnt>2
  • rownum对于rownum<n((n>1的自然数)的条件认为是成立的,所以可以找到记录
    eg:select rownum,id,n在这里插入代码片ame from Table where rownum <3 --查询两行记录
  • 查询rownum在某区间的数据,使用子查询。例如要查询rownum在第二行至第五行之间的数据,包括第二行和第五行数据,先让它返回小于等于5的记录行,然后在主查询中判断新的rownum的别名列大于等于2的记录行
    eg:select * from (select rownum cnt,id,name from Table where rownum<=5 ) where cnt>=2;
  • rownum和排序
    系统是按照记录插入时的顺序给记录排的号,rowid也是顺序分配的。如果要排序,必须使用子查询,而语句select rownum ,id,name from Table order by name;并不会按name排序
    eg:select rownum,id,name from (select * from Table order by name);
发布了52 篇原创文章 · 获赞 7 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/hyfstyle/article/details/104037478