SQL: ORDER BY Clause
The ORDER BY clause allows you to sort the records in your result set. The ORDER BY clause can only be used in SELECT statements.
译:ORDER BY允许你在结果集中对记录进行排序。ORDER BY只能够用于SELECT语句。
The syntax for the ORDER BY clause is:
译:ORDER BY的语法如下:
SELECT columns
FROM tables
WHERE predicates
ORDER BY column ASC/DESC;
FROM tables
WHERE predicates
ORDER BY column ASC/DESC;
The ORDER BY clause sorts the result set based on the columns specified. If the ASC or DESC value is omitted, the system assumed ascending order.
译:ORDER BY是根据指定的列进行排序。如果省略ASC或者DESC,系统默认为升序。
ASC indicates ascending order. (default)
DESC indicates descending order.
DESC indicates descending order.
译:ASC表明升序(默认)
DESC表明降序。
DESC表明降序。
Example #1
SELECT supplier_city
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY supplier_city;
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY supplier_city;
This would return all records sorted by the supplier_city field in ascending order.
译:结果将会以supplier_city排序的升序结果返回所有记录。
Example #2
SELECT supplier_city
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY supplier_city DESC;
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY supplier_city DESC;
This would return all records sorted by the supplier_city field in descending order.
译:以supplier_city的降序结果返回所有记录。
Example #3
You can also sort by relative position in the result set, where the first field in the result set is 1. The next field is 2, and so on.
译:你可以采用字段的相对位置作为排序,第一个字段为1,下一个为2等等。
SELECT supplier_city
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY 1 DESC;
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY 1 DESC;
This would return all records sorted by the supplier_city field in descending order, since the supplier_city field is in position #1 in the result set.
译:这样会以supplier_city的降序返回所有结果,因为supplier_city在结果集中的位置是#1。
Example #4
SELECT supplier_city, supplier_state
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY supplier_city DESC, supplier_state ASC;
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY supplier_city DESC, supplier_state ASC;
This would return all records sorted by the supplier_city field in descending order, with a secondary sort by supplier_state in ascending order.
译:返回以supplier_city为降序、supplier_state为二级升序的结果。

本文详细介绍了 SQL 中 ORDER BY 子句的使用方法,包括如何按升序(ASC)和降序(DESC)对查询结果进行排序,并提供了多个实际例子来帮助理解。
440

被折叠的 条评论
为什么被折叠?



