扫码一下
查看教程更方便
SQL 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 |
+----+----------+-----+-----------+----------+
以下示例将从 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语句实现该效果
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语句实现该效果。
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 |
+----+---------+-----+-----------+---------+