是否有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行.
这显示了不同的方式:
-- 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
不在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的方法.
另见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)