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

时间:2009-02-27 15:04:27

标签: mysql database keyword ansi-sql

是否有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行。

7 个答案:

答案 0 :(得分:36)

this shows the different ways:

-- 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

答案 1 :(得分:22)

不在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的方法。

答案 2 :(得分:12)

另见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)

答案 3 :(得分:3)

我不相信。我所知道的所有数据库都使用特定于供应商的关键字来实现该功能。

答案 4 :(得分:1)

添加到@ jle的answer

  • SQLite支持LIMIT(MySQL / PostgreSQL)
  • InterBase / Firebird支持SELECT FIRSTSKIP(如Informix)

另见Emulate MySQL LIMIT clause in Microsoft SQL Server 2000

答案 5 :(得分:1)

HSQL / H2使用像MySQL这样的LIMIT

答案 6 :(得分:0)