场景:在按照条件查询后,排序按照不同的条件排序,以及同一个条件 正序和倒序排序。可以考虑使用。
遇到的排序条件:按照直播的状态,根据条件排序。直播的状态包括:直播、置顶、预告、回放、过期预告。排序条件为:多直播按照 开始时间倒序排序,置顶按照置顶时间正序排序,预告按照离当前时间越近的倒序排序,回放按照开始时间倒序、过期预告按照离当前时间越近正序排序。
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 注意一点:后面的排序条件就是 你最终的排序条件。