一、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