简单地说,TOP N问题就是:在SELECT中,仅选择按照某(些)列排序后TOP N的纪录. 考虑到等值问题,又可以分为两种: 一是仅仅返回N条纪录(M 1), 二是还包括所有于第N条等值的纪录(M 2). 当然最内层的子查询也可以有其他的子句, 或者TOP N也可以应用在没有ORDER BY的情况下,这样更简单.
1. SQL SERVER 7: 用 TOP N (WITH TIES)
M1:
SELECT TOP N * FROM MYTABLE ORDER BY ORD_COL;
M2:
SELECT TOP N WITH TIES * FROM MYTABLE ORDER BY ORD_COL;
注: SQL SERVER 7提供了PERCENT N WITH TIES, ACCESS 中提供了TOP N,但含义是M 2.
2. ORACLE 8i: 用 ROWNUM<=N
M1:
SELECT * FROM
( SELECT * FROM MYTABLE ORDER BY ORD_COL DESC)
WHERE ROWNUM<=N
M2:
SELECT * FROM MYTABLE WHERE ORD_COL>=
(SELECT MIN(ORD_COL) FROM
( SELECT * FROM MYTABLE ORDER BY ORD_COL DESC)
WHERE ROWNUM<=N)
ORDER BY ORD_COL DESC
注意以下两种错误用法:
WRONG 1:
SELECT * FROM MYTABLE
WHERE ROWID<=N
ORDER BY ORD_COL DESC;
WRONG 2:(因为WHERE ROWNUM<=N 在ORDER BY 前执行)
SELECT * FROM MYTABLE
WHERE ROWNUM<=N
ORDER BY ORD_COL DESC;
3: DB2
用FETCH FIRST N ROWS ONLY
M1:
SELECT * FROM MYTABLE
ORDER BY ORD_COL DESC
FETCH FIRST N ROWS ONLY
1. SQL SERVER 7: 用 TOP N (WITH TIES)
M1:
SELECT TOP N * FROM MYTABLE ORDER BY ORD_COL;
M2:
SELECT TOP N WITH TIES * FROM MYTABLE ORDER BY ORD_COL;
注: SQL SERVER 7提供了PERCENT N WITH TIES, ACCESS 中提供了TOP N,但含义是M 2.
2. ORACLE 8i: 用 ROWNUM<=N
M1:
SELECT * FROM
( SELECT * FROM MYTABLE ORDER BY ORD_COL DESC)
WHERE ROWNUM<=N
M2:
SELECT * FROM MYTABLE WHERE ORD_COL>=
(SELECT MIN(ORD_COL) FROM
( SELECT * FROM MYTABLE ORDER BY ORD_COL DESC)
WHERE ROWNUM<=N)
ORDER BY ORD_COL DESC
注意以下两种错误用法:
WRONG 1:
SELECT * FROM MYTABLE
WHERE ROWID<=N
ORDER BY ORD_COL DESC;
WRONG 2:(因为WHERE ROWNUM<=N 在ORDER BY 前执行)
SELECT * FROM MYTABLE
WHERE ROWNUM<=N
ORDER BY ORD_COL DESC;
3: DB2
用FETCH FIRST N ROWS ONLY
M1:
SELECT * FROM MYTABLE
ORDER BY ORD_COL DESC
FETCH FIRST N ROWS ONLY