SQL TOP, LIMIT, FETCH FIRST 或ROWNUM语句
SQL SELECT TOP 语句
SELECT TOP
子句用于指定要返回的记录数量。
SELECT TOP
子句在有成千上万条记录的大表中很有用,返回大量的记录会影响性能。
注意:不是所有的数据库系统都支持
SELECT TOP
子句。MySQL支持LIMIT
子句来选择有限数量的记录,而Oracle使用FETCH FIRST *n* ROWS ONLY
和ROWNUM
。
SQL Server / MS Access 语法:
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
MySQL 语法:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Oracle 12 语法:
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;
较早版本的Oracle语法:
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
较早版本的Oracle语法(带ORDER BY):
SELECT *
FROM (SELECT column_name(s) FROM table_name ORDER BY column_name(s))
WHERE ROWNUM <= number;
SQL TOP, LIMIT 和 FETCH FIRST 示例
下面的SQL语句从 "Customers"表中选择前三条记录(用于SQL Server/MS Access)
SELECT TOP 3 * FROM Customers;
输出:
下面的SQL语句从 "Customers"表中选择前三条记录(用于MySQL)
SELECT * FROM Customers
LIMIT 3;
输出:
下面的SQL语句从 "Customers"表中选择前三条记录(用于Oracle)
SELECT * FROM Customers
FETCH FIRST 3 ROWS ONLY;
SQL TOP PERCENT 示例
下面的SQL语句从 "Customers"表中选择前50%的记录(针对SQL Server/MS Access)
SELECT TOP 50 PERCENT * FROM Customers;
输出:
下面的SQL语句从 "Customers"表中选择前50%的记录(用于Oracle)
SELECT * FROM Customers
FETCH FIRST 50 PERCENT ROWS ONLY;
增加一个WHERE语句
下面的SQL语句从 "Customers"表中选择前三条记录,其中国家是 "Germany"(针对SQL Server/MS Access)
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
输出:
下面的SQL语句从 "Customers"表中选择前三条记录,其中国家是 "Germany"(针对MySQL)
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;
输出:
下面的SQL语句从 "Customers"表中选择前三条记录,其中国家是 "Germany"(针对Oracle)
SELECT * FROM Customers
WHERE Country='Germany'
FETCH FIRST 3 ROWS ONLY;