表达式 SELECT TOP 用于指定要选择的记录数。
SQL SELECT TOP 对于具有数千条记录的大型表很有用,因为返回大量记录会影响系统性能。
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number
SELECT *
FROM (SELECT column_name(s) FROM table_name ORDER BY column_name(s))
WHERE ROWNUM <= number
以下是“Northwind”数据库的“Customers”表中的示例:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 5021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 5023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
以下 SQL 语句从“Customers”表中选择前三条记录(对于 SQL Server/MS Access):
SELECT TOP 3 *
FROM Customers
以下 SQL 语句显示了 MySQL 的等效示例:
Run SQLSELECT *
FROM Customers
LIMIT 3
以下 SQL 语句显示了 Oracle 的等效示例:
SELECT *
FROM Customers
FETCH FIRST 3 ROWS ONLY
以下 SQL 语句从 Customers 表中选择前 50% 的记录(对于 SQL Server/MS Access):
SELECT TOP 50 PERCENT *
FROM Customers
以下 SQL 语句显示了 Oracle 的等效示例:
SELECT *
FROM Customers
FETCH FIRST 50 PERCENT ROWS ONLY
以下 SQL 语句从“Customers”表中选择国家/地区为“Germany”的前三个记录(对于 SQL Server/MS Access):
SELECT TOP 3 *
FROM Customers
WHERE Country = 'Germany'
以下 SQL 语句显示了 MySQL 的等效示例:
Run SQLSELECT *
FROM Customers
WHERE Country = 'Germany'
LIMIT 3
以下 SQL 语句显示了 Oracle 的等效示例:
SELECT *
FROM Customers
WHERE Country = 'Germany'
FETCH FIRST 3 ROWS ONLY