SQL TOP,LIMIT,ROWNUM子句
SQL TOP子句用於從表中獲取一個TOP N數字或X%的紀錄。
注意: 不是所有的數據庫都支持TOP子句。例如,MySQL使用LIMIT子句來獲取記錄;Oracle使用ROWNUM獲取有限的記錄數。
語法
SELECT語句TOP子句的基本語法將如下所示:
SELECT TOP number|percent column_name(s) FROM table_name
WHERE [condition]
例子:
考慮CUSTOMERS表具有以下記錄:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+
以下是SQL SERVER服務器,這將取前客戶表的前3個記錄的例子:
SQL> SELECT TOP 3 * FROM CUSTOMERS;
這將產生以下結果:
+----+---------+-----+-----------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+---------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+---------+-----+-----------+---------+
如果你使用MySQL服務器,然後在這裏是一個等效的例子:
SQL> SELECT * FROM CUSTOMERS
LIMIT 3;
這將產生以下結果:
+----+---------+-----+-----------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+---------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+---------+-----+-----------+---------+
如果您使用Oracle服務器,然後在這裏是一個等效的例子:
SQL> SELECT * FROM CUSTOMERS
WHERE ROWNUM <= 3;
這將產生以下結果:
+----+---------+-----+-----------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+---------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+---------+-----+-----------+---------+