/*
语法:
select 查询列表
from 表名
【where 筛选条件】
order by 排序的字段或表达式
特点:
1、asc代表的是升序,可以省略
desc代表的是降序
2、order by子句可以支持 单个字段、别名、表达式、函数、多个字段
3、order by子句在查询语句的最后面,除了limit子句
*/
SELECT * FROM employees ORDER BY salary DESC
SELECT *
FROM employees
WHERE department_id>=90
ORDER BY employee_id DESC
SELECT ,salary 12 (1+IFNULL(commission_pct,0))
FROM employees
ORDER BY salary 12*(1+IFNULL(commission_pct,0)) DESC
SELECT ,salary 12*(1+IFNULL(commission_pct,0)) 年薪
FROM employees
ORDER BY 年薪 ASC
SELECT LENGTH(last_name),last_name
FROM employees
ORDER BY LENGTH(last_name) DESC
SELECT *
FROM employees
ORDER BY salary DESC,employee_id ASC
1、单列排序SELECT * FROM test1 ORDER BY date_time
默认升序,降序后面接"DESC"即可。
2、多列排序
SELECT * FROM test1 ORDER BY `status`, date_time DESC
首先按`status`字段排序,若`status`相等,则按data_time排序。
3、自定义排序
SELECT * FROM test1 ORDER BY FIELD(`status`, 3, 2, 4, 1, 5), date_time DESC
使用"FIELD()"函数,可指定顺序。
4、其他条件排序
先按大于等于当前时间升序,再按小于当前时间降序,支持分页。
SELECT * FROM test1 ORDER BY date_time <NOW(), IF(date_time <NOW(), 0, date_time), date_time DESC
附加SQL脚本:
CREATE TABLE `test1` (`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`date_time` datetime NOT NULL,
`status` int(5) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
INSERT INTO `test1` VALUES
(NULL, '测试1', '2018-03-05 11:09:00', 1),(NULL, '测试2', '2018-03-06 11:09:00', 1),(NULL, 'abc', '2018-03-07 11:09:00', 1),
(NULL, 'def', '2018-04-08 11:09:00', 2),(NULL, '李某某', '2018-04-17 11:09:00', 1),(NULL, '饭某某', '2018-04-20 13:09:00', 2),
(NULL, '赵', '2018-04-20 01:09:00', 4),(NULL, '倩', '2018-04-28 11:09:00', 2),(NULL, 'andy', '2018-04-30 11:09:00', 1),
(NULL, 'tony', '2018-05-08 11:09:00', 4),(NULL, 'tom', '2018-05-07 11:09:00', 3),(NULL, 'bill', '2018-05-18 11:09:00', 3),
(NULL, 'james', '2018-06-07 11:09:00', 4),(NULL, 'anthony', '2018-06-18 11:09:00', 2),(NULL, '盖茨', '2018-04-21 11:09:00', 1),
(NULL, '部长', '2018-04-24 11:09:00', 4),(NULL, '李总', '2018-04-20 11:09:00', 5),(NULL, '张总', '2018-04-29 11:09:00', 2),
(NULL, '王总', '2018-04-19 11:09:00', 3),(NULL, '唐总', '2018-05-01 11:09:00', 2)
参考的这篇文档Mysql排序方式
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)