当前位置:  开发笔记 > 编程语言 > 正文

是否有MYSQL LIMIT关键字的ANSI SQL替代品?

如何解决《是否有MYSQLLIMIT关键字的ANSISQL替代品?》经验,为你挑选了3个好方法。

是否有MYSQL LIMIT关键字的ANSI SQL替代品?

LIMIT关键字限制SELECT返回的行数,例如:

SELECT * FROM People WHERE Age > 18 LIMIT 2;

返回2行.

SELECT * FROM People WHERE Age > 18 LIMIT 10, 2;

在前10后返回2行.



1> jle..:

这显示了不同的方式:

-- DB2
select * from table fetch first 10 rows only 
-- Informix 
select first 10 * from table 
-- Microsoft SQL Server and Access 
select top 10 * from table 
-- MySQL and PostgreSQL 
select * from table limit 10 
-- Oracle 
select * from (select * from table) where rownum <= 10


我一直认为Oracle让你做这样的子选择是荒谬的,但rownum属性是在用ORDER BY重新排序之前分配的.
+1精彩的总结!SQLite支持LIMIT,如MySQL/PostgreSQL.InterBase/Firebird支持SELECT FIRST和SKIP,如Informix.

2> bobince..:

不在SQL:1999中.

您可以在以后的标准中使用两种可能的方法,在当今的DBMS中通常支持水平较低.

在SQL:2008中,您可以使用DB/2语法:

SELECT * FROM things
ORDER BY smell
FETCH FIRST n ROWS ONLY

这仅适用于"LIMIT n"而不适用于扩展的"LIMIT m,n"偏移语法.在SQL:2003中,您可以使用窗口函数,它可以支持扩展语法但是是超级PITA:

SELECT * FROM (
    SELECT *, ROW_NUMBER() OVER (ORDER BY smell) AS rn,
    FROM things
)
WHERE rn<=n -- or rn BETWEEN m+1 AND m+n

您现在通常会使用特定于DBMS的方法.



3> groovehunter..:

另见http://en.wikipedia.org/wiki/Select_(SQL)#FETCH_FIRST_clause

SELECT * FROM T LIMIT 10 OFFSET 20 -- Netezza, MySQL, PostgreSQL (also supports the standard, since version 8.4), SQLite, HSQLDB, H2

SELECT * from T WHERE ROWNUM <= 10 -- Oracle (also supports the standard, since Oracle8i)

SELECT FIRST 10 * from T -- Ingres

SELECT FIRST 10 * FROM T order by a -- Informix

SELECT SKIP 20 FIRST 10 * FROM T order by c, d -- Informix (row numbers are filtered after order by is evaluated. SKIP clause was introduced in a v10.00.xC4 fixpack)

SELECT TOP 10 * FROM T -- MS SQL Server, Sybase ASE, MS Access

SELECT TOP 10 START AT 20 * FROM T -- Sybase SQL Anywhere (also supports the standard, since version 9.0.1)

SELECT FIRST 10 SKIP 20 * FROM T -- Interbase, Firebird

SELECT * FROM T ROWS 20 TO 30 -- Firebird (since version 2.1)

SELECT * FROM T
WHERE ID_T > 10 FETCH FIRST 10 ROWS ONLY -- DB2

SELECT * FROM T
WHERE ID_T > 20 FETCH FIRST 10 ROWS ONLY -- DB2 (new rows are filtered after comparing with key column of table T)

推荐阅读
我我檬檬我我186
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有