【MySQL】order by 高级用法 case when (字段多值自定义排序)

数据模拟(table)

gmt_create field state(0:处理中,1:已完成,2:已拒绝,3:已中止)
2023-10-18 07:27:35 xiaoming 0
2023-10-19 08:24:53 xiaohong 1
2023-10-20 09:12:14 xiaolan 3
2023-10-21 10:16:28 xiaogang 2
2023-10-22 08:14:13 xiaoqiang 0
2023-10-23 09:54:57 xiaolv 1
2023-10-24 07:33:43 xiaoli 2

目标

查询列表把 处理中的数据 放到最前面,之后再按 创建时间大到小 排序,效果图如下

gmt_create field state(0:处理中,1:已完成,2:已拒绝,3:已中止)
2023-10-22 08:14:13 xiaoqiang 0
2023-10-18 07:27:35 xiaoming 0
2023-10-24 07:33:43 xiaoli 2
2023-10-23 09:54:57 xiaolv 1
2023-10-21 10:16:28 xiaogang 2
2023-10-20 09:12:14 xiaolan 3
2023-10-19 08:24:53 xiaohong 1

SQL 编写

SELECT * 
FROM table
ORDER BY (CASE WHEN state = 0 THEN 1 ELSE 2 END), gmt_create DESC

参考

mysql 某列指定值靠前排序:order by 高级用法之 case when

你可能感兴趣的:(#,MySQL,mysql)