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 | +----+---------+-----+-----------+---------+