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)
我不相信。我知道的所有数据库都使用特定于供应商的关键字来实现该功能。
添加到@jle的答案:
LIMIT
(MySQL/PostgreSQL)SELECT FIRST
和SKIP
(如 Informix)HSQL/H2 像 MySQL 一样使用 LIMIT
让我在这里链接一个相关的 SO 问题,Lukas Eder给出了很好的答案,bobince 给出了另一个很好的答案:
编辑:更多好的参考链接,在类似情况下值得一看: