場景:在按照條件查詢后,排序按照不同的條件排序,以及同一個條件 正序和倒序排序。可以考慮使用。
遇到的排序條件:按照直播的狀態,根據條件排序。直播的狀態包括:直播、置頂、預告、回放、過期預告。排序條件為:多直播按照 開始時間倒序排序,置頂按照置頂時間正序排序,預告按照離當前時間越近的倒序排序,回放按照開始時間倒序、過期預告按照離當前時間越近正序排序。
sql語句為:
SELECT l.id, l.title, l.description, l.picture, l.is_dist_public,l.pre_start_time, l.create_time, ( CASE WHEN l.live_status = 'NOTICE' THEN date_format( l.pre_start_time, '%Y-%m-%d %H:%i:%s' ) ELSE date_format( l.start_time, '%Y-%m-%d %H:%i:%s' ) END ) start_time, r.top_time, l.category, l.live_status, l.create_user, l.zm_account_id, l.source, ( CASE WHEN l.live_status = 'LIVING' THEN 1 WHEN ( r.is_top = 1 AND l.live_status <> 'LIVING' ) THEN 2 WHEN l.live_status = 'NOTICE' AND pre_start_time >= now() THEN 3 WHEN l.live_status = 'NOTICE' AND pre_start_time < now() THEN 5 WHEN l.live_status = 'PLAYBACK' THEN 4 END ) AS sort, r.is_top FROM live l LEFT JOIN live_zm_account_rel r ON r.live_id = l.id AND l.live_status != 'PRE_LIVE' WHERE 1 = 1 AND r.is_enabled = 1 AND r.is_delete = 0 AND l.is_enabled = 1 AND l.is_delete = 0 AND r.zm_account_id = '9f7aa1cec50e4b368e69c4f5c14c3fcf' ORDER BY sort ASC, CASE WHEN sort = 1 then l.start_time END DESC, CASE WHEN sort = 2 then r.top_time END DESC, CASE WHEN sort = 3 then l.pre_start_time END ASC, CASE WHEN sort = 4 then l.start_time END DESC, CASE WHEN sort = 5 then l.pre_start_time END DESC LIMIT 15
CASE when then 注意一點:后面的排序條件就是 你最終的排序條件。
