MySQL提供两种排序的方式,分别为 单字段排序和 多字段排序。
1.准备
CREATE TABLE emp
(
empno INT PRIMARY KEY,
ename VARCHAR(10),
sal INT,
deptno INT
) ENGINE = INNODB DEFAULT CHARSET = utf8;
INSERT INTO emp VALUES (1,'smith',1800,20);
INSERT INTO emp VALUES (2,'allen',1500,10);
INSERT INTO emp VALUES (3,'ward',1600,30);
INSERT INTO emp VALUES (4,'jones',2000,30);
INSERT INTO emp VALUES (5,'martin',1800,10);
INSERT INTO emp VALUES (6,'blake',1800,30);
2.语法
order by a --a升序
order by a asc --a升序
order by a desc --a降序
order by a,b --a和b都是升序
order by a,b desc --a升序,b降序
order by a desc,b --a降序,b升序
order by a desc,b desc --a和b都是降序
3.示例
-- 按照sal升序排序
SELECT * FROM emp ORDER BY sal;
-- 等价于
SELECT * FROM emp ORDER BY sal ASC;
-- 按照sal降序排序
SELECT * FROM emp ORDER BY sal DESC;
-- 先按照deptno降序排序,如果deptno相同,在按照sal升序排序
SELECT * FROM emp ORDER BY deptno DESC,sal;