gpt4 book ai didi

sql - SQL中的LIMIT语句有多普遍?

转载 作者:太空狗 更新时间:2023-10-30 01:40:51 25 4
gpt4 key购买 nike

我正在推广 Django 数据库复制应用程序,它使用以下语句:

SELECT %s FROM %s LIMIT 1

获取 1 行并使用 Python DBAPI 来描述字段,它适用于 ORACLE 和 MySQL,但是,LIMIT 语句的跨平台程度如何?

最佳答案

LIMIT 已经在各种开源数据库中变得相当流行,但不幸的是,事实是 OFFSET 分页一直是所有这些数据库中标准化程度最低的 SQL 功能, 最迟在 SQL:2008 中被标准化.

在那之前,jOOQ user manual page on the LIMIT clause显示了如何在每种 SQL 方言中形成各种等效语句:

-- MySQL, H2, HSQLDB, Postgres, and SQLite
SELECT * FROM BOOK LIMIT 1 OFFSET 2

-- CUBRID supports a MySQL variant of the LIMIT .. OFFSET clause
SELECT * FROM BOOK LIMIT 2, 1

-- Derby, SQL Server 2012, Oracle 12c, SQL:2008 standard
-- Some need a mandatory ORDER BY clause prior to OFFSET
SELECT * FROM BOOK [ ORDER BY ... ] OFFSET 2 ROWS FETCH NEXT 1 ROWS ONLY

-- Ingres
SELECT * FROM BOOK OFFSET 2 FETCH FIRST 1 ROWS ONLY

-- Firebird
SELECT * FROM BOOK ROWS 2 TO 3

-- Sybase SQL Anywhere
SELECT TOP 1 ROWS START AT 3 * FROM BOOK

-- DB2 (without OFFSET)
SELECT * FROM BOOK FETCH FIRST 1 ROWS ONLY

-- Sybase ASE, SQL Server 2008 (without OFFSET)
SELECT TOP 1 * FROM BOOK

现在,这些都非常简单,对吧?讨厌的部分来了,当你必须模仿它们时:

-- DB2 (with OFFSET), SQL Server 2008 (with OFFSET), 
SELECT * FROM (
SELECT BOOK.*,
ROW_NUMBER() OVER (ORDER BY ID ASC) AS RN
FROM BOOK
) AS X
WHERE RN > 2
AND RN <= 3

-- DB2 (with OFFSET), SQL Server 2008 (with OFFSET)
-- When the original query uses DISTINCT!
SELECT * FROM (
SELECT DISTINCT BOOK.ID, BOOK.TITLE
DENSE_RANK() OVER (ORDER BY ID ASC, TITLE ASC) AS RN
FROM BOOK
) AS X
WHERE RN > 2
AND RN <= 3

-- Oracle 11g and less
SELECT *
FROM (
SELECT b.*, ROWNUM RN
FROM (
SELECT *
FROM BOOK
ORDER BY ID ASC
) b
WHERE ROWNUM <= 3
)
WHERE RN > 2

Read about the ROW_NUMBER() vs. DENSE_RANK() rationale here

选择你的毒药 ;-)

关于sql - SQL中的LIMIT语句有多普遍?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1528604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com