📅  最后修改于: 2020-12-29 04:35:18             🧑  作者: Mango
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上的示例,它将从CUSTOMERS表中获取前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 |
+----+---------+-----+-----------+---------+