且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何选择SQL数据库表中的第n行?

更新时间:2023-12-01 10:09:40

有很多方法可以做到这一点

There are ways of doing this in optional parts of the standard, but a lot of databases support their own way of doing it.

一个非常好的网站,介绍这个和其他的东西是 http://troels.arvin.dk/db/rdbms/#select-limit

A really good site that talks about this and other things is http://troels.arvin.dk/db/rdbms/#select-limit.

基本上,PostgreSQL和MySQL支持非标准:

Basically, PostgreSQL and MySQL supports the non-standard:

SELECT...
LIMIT y OFFSET x 

Oracle,DB2和MSSQL支持标准窗口函数:

Oracle, DB2 and MSSQL supports the standard windowing functions:

SELECT * FROM (
  SELECT
    ROW_NUMBER() OVER (ORDER BY key ASC) AS rownumber,
    columns
  FROM tablename
) AS foo
WHERE rownumber <= n

(我刚刚从上面链接的网站复制,因为我从未使用过这些数据库)

(which I just copied from the site linked above since I never use those DBs)

更新:的PostgreSQL 8.4的标准窗口函数是支持的,所以期望第二个例子也为PostgreSQL工作。

Update: As of PostgreSQL 8.4 the standard windowing functions are supported, so expect the second example to work for PostgreSQL as well.