mysql 根据某字段特定值排序

一、case when方式

比如:

表 :user

字段:orders (值为 1,2,3)

要求根据字段 orders 按2 -> 1 -> 3 排序

使用以下语句实现

SELECT *
FROM user
ORDER BY CASE  orders  WHEN 2 THEN 1 WHEN 1 THEN 2 WHEN 3 THEN 3 END;

二、union方式

有下图这些数据,done、process、failure三种状态,怎么用sql语句根据顺序排序,并且同样的process 状态的数据要根据date_created 倒序排,done和failure状态的根据date_created顺序排

(select * from 表名版权 where status='process' order by date_created desc)
union all
(select * from 表名 where status='done' order by date_created asc)
union all
(select * from 表名 where status='failure' order by date_created asc)

三、自定义排序

MySQL中的排序ORDER BY 除了可以用ASC和DESC,还可以自定义字符串/数字来实现排序。

格式如下:

SELECT * FROM table ORDER BY FIELD(status,1,2,0);

这样子写的话,返回的结果集是按照字段status的1、2、0进行排序的,当然,也可以对字符串进行排序。

原理如下:

FIELD()函数是将参数1的字段对后续参数进行比较,并返回1、2、3等等,如果遇到null或者没有在结果集上存在的数据,则返回0,然后根据升序进行排序。

select * from t_dit_task order by field(status, 1001, 1000, 1002);

3    test3    1001
5    test5    1001
6    test6    1001
1    test1    1000
2    test2    1000
4    test4    1000
9    test9    1000
7    test7    1002
8    test8    1002



select * from t_dit_task order by field(status, 1001, 1000, 1002) desc;

7    test7    1002
8    test8    1002
1    test1    1000
2    test2    1000
4    test4    1000
9    test9    1000
3    test3    1001
5    test5    1001
6    test6    1001

另外一篇博客 https://www.cnblogs.com/178mz/p/6428958.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章