直播中
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 前執(zhí)行)
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
M2:
沒有找到,因為DB2不允許在FROM中嵌套有ORDER BY子句的子查詢.
還不清楚ORACLE的M 2有沒有更好的辦法,以及其他的DBMS如何實現(xiàn)TOP N操作,請其他朋友補充.
----------------------------------------------------------------------------------
各語句已經(jīng)測試過, EXAMPLE:
create table mytable(mykey int, ord_col int);
insert into mytable values(1, 100);
insert into mytable values(2, 100);
insert into mytable values(3, 99);
insert into mytable values(4, 101);
insert into mytable values(5, 101);
fang 6/23/2000