数据库
首页 > 数据库> > 【MySQL】排序与分页

【MySQL】排序与分页

作者:互联网

1.排序

1.1 升序和降序

SELECT employee_id,first_name,salary
FROM employees
ORDER BY salary;

SELECT employee_id,first_name,salary
FROM employees
ORDER BY salary desc;

image

1.2 单列排序

只根据一个字段进行排序

SELECT last_name,job_id,department_id,hire_date
FROM employees
ORDER BY hire_date;

SELECT last_name,job_id,department_id,hire_date
FROM employees
ORDER BY hire_date DESC;

SELECT employee_id,last_name,salary*12 annsal
FROM employees
ORDER BY annsal;

1.3 多列排序

ASC可省略

SELECT last_name,department_id,salary
FROM employees
ORDER BY department_id ASC,salary DESC;

image

2.分页

LIMIT n,m
#前10条记录
SELECT * FROM employees LIMIT 0,10;
#或者
SELECT * FROM employees LIMIT 10;

#第11至第20条记录
SELECT * FROM employees LIMIT 10,10;

#第21至第30条记录
SELECT * FROM employees LIMIT 20,10;

MySQL8.0中可以使用"LIMIT 3 OFFSET 4",表示从第5条记录开始后面的3条记录,跟"LIMIT 4,3" 效果相同

分页显示公式:(pageIndex-1)*pageSize,pageSize

SELECT * FROM table
LIMIT (pageIndex-1)*pageSize,pageSize;

LIMIT字句必须放在整个SELECT语句的最后

3.拓展

不同的数据库中使用的关键字不同,MySQL中使用的是LIMIT

SELECT TOP 5 name,hp_max
FROM heros
ORDER BY hp_max DESC;
SELECT name,hp_max
FROM heros
ORDER BY hp_max DESC FETCH FIRST 5 ROWS ONLY;
SELECT rownum, last_name,salary
FROM employees
WHERE rownum<5
ORDER BY salary DESC;

取出排序后的数据

SELECT rownum,last_name,salary
FROM(
	SELECT last_name,salary
	FROM employees
	ORDER BY salary DESC)
WHERE rownum<10;

标签:salary,name,employees,LIMIT,MySQL,排序,ORDER,SELECT,分页
来源: https://www.cnblogs.com/zhishu/p/16416514.html