文章目錄
1. MySQL查詢結果排序,先升序 再將空值排在最後
is null 是將值爲null和不爲null分組
select * from table order by sortnum is null,sortnum asc;
2. if(isnull(sortnum),1,0),sortnum asc
select * from table order by if(isnull(sortnum),1,0),sortnum asc;
3. MySQL order by case when查詢結果排序,先區分排序優先級升序,然後空值排最後,最後升序
last_visit_dt = ‘1900-01-01 00:00:00’ 的優先級最低設置爲1000,其他的優先級高,設置爲0
select * from table order by case when table.last_visit_dt = '1900-01-01 00:00:00' then 1000 else 0 end, sortnum is null,sortnum asc;
4. mybatis 動態SQL根據不同的情況進行不同的排序order by
- 使用if test
比較sortMode值等於字符串1,使用雙引號嵌套單引號未生效<if test “sortMode == ‘1’”>;後來使用單引號嵌套雙引號正常:<if test ‘sortMode == “1”’>
select * from table t
<if test 'sortMode == "1"'>
order by t.building_cd asc, t.room_no asc
</if>
<if test 'sortMode == "2"'>
order by t.building_cd asc, t.room_no asc
</if>
- 使用choose when otherwise
類似於Java 的 switch 語句,choose 爲 switch,when 爲 case,otherwise 則爲 default。
<choose>
<when test="enVersion != null and enVersion =='0'">
order by a.weight desc ,str_to_date(a.publish_date, '%Y年%m月%d日') desc
</when>
<otherwise>
order by a.weight desc ,str_to_date(a.publish_date, '%d %M %Y') desc
</otherwise>
</choose>