排序ORDER BY
默认查询返回地数据顺序,是数据先后添加的顺序
排序实现方法
使用ORDER BY
对查询的数据进行排序,默认是升序排列:
- 升序:
ASC
(ascend)
- 降序:
DESC
(descend)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| SELECT employee_id, last_name, salary FROM employees ORDER BY salary DESC; + | employee_id | last_name | salary | + | 100 | King | 24000.00 | | 101 | Kochhar | 17000.00 | | 102 | De Haan | 17000.00 |
SELECT employee_id, last_name, salary FROM employees ORDER BY salary ASC; + | employee_id | last_name | salary | + | 132 | Olson | 2100.00 | | 128 | Markle | 2200.00 | | 136 | Philtanker | 2200.00 |
|
使用列的别名进行排序
1 2 3 4 5 6 7 8 9 10 11
| # 以annual_sal为年工资(salary*12 )的别名进行排序 SELECT employee_id, salary, salary*12 annual_sal FROM employees ORDER BY annual_sal ASC; + | employee_id | salary | annual_sal | + | 132 | 2100.00 | 25200.00 | | 128 | 2200.00 | 26400.00 | | 136 | 2200.00 | 26400.00 | | 127 | 2400.00 | 28800.00 |
|
注意:
列的别名只能在ORDER BY
中使用,不能在WHERE
中使用:
一条查询语句执行时,首先执行FROM
和WHERE
语句,再执行SELECT
(SELECT中声明了别名),最后执行ORDER BY
多级排序
1 2 3 4 5 6 7 8 9 10 11 12
| # 按照department_id降序排列,salary升序排列 SELECT employee_id, salary, department_id FROM employees ORDER BY department_id DESC, salary ASC; + | employee_id | salary | department_id | + | 206 | 8300.00 | 110 | | 205 | 12000.00 | 110 | | 113 | 6900.00 | 100 | | 111 | 7700.00 | 100 | | 112 | 7800.00 | 100 |
|
分页LIMIT
分页实现方法
使用LIMIT
关键字:
LIMIT [offset,] rows
:
offset
为偏移量(默认从0开始)
rows
为返回行的最大行数。为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为-1
1 2 3 4 5 6 7 8 9
| # 显示前20条记录 SELECT employee_id, last_name FROM employees LIMIT 0, 20;
# 显示第21-40条记录 SELECT employee_id, last_name FROM employees LIMIT 20, 20;
|
MySQL 8.0新特性
MySQL 8.0新特性即LIMIT 最大行数 OFFSET 偏移量
1 2 3 4 5 6 7 8 9
| SELECT employee_id, last_name FROM employees LIMIT 2 OFFSET 41; + | employee_id | last_name | + | 141 | Rajs | | 142 | Davies | +
|