最近在公司遇到一個
一個復雜的根據時間排序算法的sql編寫:
情況是這樣的,公司平台創建的賽事,在賽事列表展示的時候要進行這樣的排序:
賽事都有開賽時間:
列表從上到下,按比賽日期【今日開賽>未開賽>已開賽】排,未開賽時間正序,已開賽時間正序:
解決的思路就是根據 order by 后面使用case when .. then.. / when .. then.. end 可以把多個情況進行排列
我解決的sql如下:
SELECT
w.match_event_id matchEventId,w.start_time startTime, w.match_address matchAddress, w.create_time createTime,
FROM
w_match w INNER JOIN m_event m_e on m_e.match_event_id = w.match_event_id
WHERE w.is_used = 1 and m_e.event_guntime is not null
order by case when DATEDIFF(m_e.event_guntime,now()) <![CDATA[ = ]]> 0 then 0
when DATEDIFF(m_e.event_guntime,now()) <![CDATA[ > ]]> 0 then 1
when DATEDIFF(m_e.event_guntime,now()) <![CDATA[ < ]]> 0 then 2
end
,m_e.event_guntime asc limit 0,20
說明: w_match和m_event是我在項目中需要用到的兩個表:
order by 后面 使用 case when .. then 數字越小排的越靠前
when .. then 數字越大排的越靠后
end
,m_e.m_e.event_guntime 按賽事開賽時間正序來排