近日工作中有個(gè)需求为流,是將輪播圖列表按使用中航攒、未使用磺陡、已過期三種狀態(tài)來順序顯示。
表的結(jié)構(gòu):
我的處理辦法是:
將使用中屎债、未使用仅政、已過期三種數(shù)據(jù)分別取出,然后通過union all來合并查詢結(jié)果盆驹。由于形成的最終結(jié)果需要按狀態(tài)排序圆丹,就需要對查詢的結(jié)果插入新字段,以方便處理排序問題躯喇。
具體sql如下:
SELECT * from
(
SELECT t.*, 1 as `vol` FROM rotate_banner as t WHERE DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%S') > t.start_time AND DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%S') < t.end_time and state=0
union all
SELECT t.*, 2 as `vol` FROM rotate_banner as t WHERE DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%S') < t.start_time and state=0
union all
SELECT t.*, 3 as `vol` FROM rotate_banner as t WHERE DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%S') > t.end_time and state=0
) as a order by vol limit 30 offset 0;