展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

mysql基础(四):排序与分页

  • 排序规则
ASC(ascend): 升序
DESC(descend):降序
ORDER BY 子句在SELECT语句的结尾
  • 代码案例
# 按照salary从高到低的顺序显示员工信息
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC;

# 按照salary从低到高的顺序显示员工信息
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary ASC;

# 如果在ORDER BY 后没有显式指名排序的方式的话,则默认按照升序排列
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary; 

# 使用列的别名,进行排序
SELECT employee_id, salary, salary * 12 annual_sal
FROM employees
ORDER BY annual_sal;

# 错误案例:
# 列的别名只能在 ORDER BY 中使用,不能在WHERE中使用。如下方式会报错
SELECT employee_id, salary, salary * 12 annual_sal
FROM employees
WHERE annual_sal > 81600;

# WHERE 需要声明在FROM后,ORDER BY之前
SELECT employee_id, salary
FROM employees
WHERE department_id IN (50,60,70)
ORDER BY department_id DESC;

# 二级排序:显示员工信息,按照department_id的降序排列,salary的升序排列
SELECT employee_id, salary, department_id
FROM employees
ORDER BY department_id DESC, salary ASC;
  • 分页规则
# 显示第几条到第几条
LIMIT [位置偏移量,] 行数

# 显示第几页的所有
分页显式公式:(当前页数-1)*每页条数,每页条数
  • 代码案例
# 每页显示20条记录,此时显示第1页
SELECT employee_id, last_name
FROM employees
LIMIT 0, 20;

# 每页显示20条记录,此时显示第2页
SELECT employee_id, last_name
FROM employees
LIMIT 20, 20;

# 每页显示20条记录,此时显示第3页
SELECT employee_id, last_name
FROM employees
LIMIT 40, 20;

# 每页显示pageSize条记录,此时显示第pageNo页:
# 公式:LIMIT (pageNo-1) * pageSize,pageSize;

# LIMIT的格式: 严格来说:LIMIT 位置偏移量,条目数

# 结构"LIMIT 0,条目数" 等价于 "LIMIT 条目数"
SELECT employee_id, last_name, salary
FROM employees
WHERE salary > 6000
ORDER BY salary DESC
#limit 0, 10;    # 写法1
LIMIT 10;

# 表里有107条数据,我们只想要显示第 32、33 条数据
SELECT employee_id, last_name
FROM employees
LIMIT 31, 2;

# MySQL8.0新特性:LIMIT ... OFFSET ...

# 表里有107条数据,我们只想要显示第 32、33 条数据
SELECT employee_id, last_name
FROM employees
LIMIT 2 OFFSET 31;

# 查询员工表中工资最高的员工信息
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC
#limit 0, 1
LIMIT 1;
课后练习
# 查询员工的姓名和部门号和年薪,按年薪降序,按姓名升序显示 
SELECT last_name, department_id, salary * 12 annual_salary
FROM employees
ORDER BY annual_salary DESC, last_name ASC;

# 选择工资不在 8000 到 17000 的员工的姓名和工资,按工资降序,显示第21到40位置的数据 
SELECT last_name, salary
FROM employees
WHERE salary NOT BETWEEN 8000 AND 17000
ORDER BY salary DESC
LIMIT 20, 20;

# 查询邮箱中包含 e 的员工信息,并先按邮箱的字节数降序,再按部门号升序
SELECT employee_id, last_name, email, department_id
FROM employees
#where email like '%e%'    # 写法1
WHERE email REGEXP '[e]'
ORDER BY LENGTH(email) DESC,department_id;
posted @ 2022-05-27 13:26  DogLeftover  阅读(21)  评论(0编辑  收藏  举报