SQL 基础排序
SQL 基础排序 - ORDER BY 子句
在 SQL 中,ORDER BY
子句用于对查询结果进行排序。通过 ORDER BY
子句,你可以根据一个或多个列对结果集进行升序或降序排列。这在处理大量数据时非常有用,可以帮助你更清晰地查看和分析数据。
1. ORDER BY
子句的使用
ORDER BY
子句的基本语法如下:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC];
column1
:指定要排序的列名。ASC
:表示按升序排序(默认值)。DESC
:表示按降序排序。
2. 多列排序
ORDER BY
子句也可以根据多个列进行排序。语法如下:
ORDER BY column1 ASC, column2 DESC;
示例
假设有一个 employees
表,包含以下数据:
1 | Alice | Smith | 60000 | 101 |
2 | Bob | Johnson | 70000 | 101 |
3 | Charlie | Brown | 50000 | 102 |
4 | David | Davis | 80000 | 102 |
5 | Eve | White | 90000 | 103 |
单列排序
查询所有员工,并按工资升序排序:
SELECT employee_id, first_name, last_name, salary
FROM employees
ORDER BY salary ASC;
结果:
3 | Charlie | Brown | 50000 |
1 | Alice | Smith | 60000 |
2 | Bob | Johnson | 70000 |
4 | David | Davis | 80000 |
5 | Eve | White | 90000 |
查询所有员工,并按工资降序排序:
SELECT employee_id, first_name, last_name, salary
FROM employees
ORDER BY salary DESC;
结果:
5 | Eve | White | 90000 |
4 | David | Davis | 80000 |
2 | Bob | Johnson | 70000 |
1 | Alice | Smith | 60000 |
3 | Charlie | Brown | 50000 |
多列排序
查询所有员工,并先按部门 ID 升序排序,再按工资降序排序:
SELECT employee_id, first_name, last_name, salary, department_id
FROM employees
ORDER BY department_id ASC, salary DESC;
结果:
1 | Alice | Smith | 60000 | 101 |
2 | Bob | Johnson | 70000 | 101 |
3 | Charlie | Brown | 50000 | 102 |
4 | David | Davis | 80000 | 102 |
5 | Eve | White | 90000 | 103 |
使用别名排序
你也可以在 ORDER BY
子句中使用列的别名进行排序。例如:
SELECT employee_id, first_name, last_name, salary AS emp_salary
FROM employees
ORDER BY emp_salary DESC;
结果:
5 | Eve | White | 90000 |
4 | David | Davis | 80000 |
2 | Bob | Johnson | 70000 |
1 | Alice | Smith | 60000 |
3 | Charlie | Brown | 50000 |