SQL ORDER BY 关键字
SQL ORDER BY
SQL ORDER BY 关键字用于按升序或降序对结果集进行排序。
语法
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
演示数据库
下面是从示例中使用的 Products 表中选择的一部分
| ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
|---|---|---|---|---|---|
| 1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
| 2 | Chang | 1 | 1 | 24 - 12 oz bottles | 19 |
| 3 | Aniseed Syrup | 1 | 2 | 12 - 550 ml bottles | 10 |
| 4 | Chef Anton's Cajun Seasoning | 2 | 2 | 48 - 6 oz jars | 22 |
| 5 | Chef Anton's Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
DESC
ORDER BY 关键字默认按升序对记录进行排序。要按降序对记录进行排序,请使用 DESC 关键字。
按字母顺序排序
对于字符串值,ORDER BY 关键字将按字母顺序排序。
反向字母顺序
要反向排序表,请使用 DESC 关键字。
按多个列排序
以下 SQL 语句从 "Customers" 表中选择所有客户,并按 "Country" 和 "CustomerName" 列排序。这意味着它首先按国家排序,如果某些行的国家相同,则按客户名称排序。
同时使用 ASC 和 DESC
以下 SQL 语句从 "Customers" 表中选择所有客户,按 "Country" 升序排序,按 "CustomerName" 降序排序。
视频:SQL ORDER BY 关键字