最近在做項目時遇到一個問題,要對一些條件進行模糊查詢,但數據庫中保存的是數字,找了一些方法,感覺CASE WHEN比較好用。
格式:
CASE WHEN 字段=條件 THEN 結果
ELSE 其它 END
select rec.status rec_status,re_statue.sta
from
(select id,
(CASE WHEN status = 0 THEN '未領取 '
WHEN status = 1 THEN '招聘中 '
WHEN status = 2 THEN '招聘名額未滿'
WHEN status = 3 THEN '完成招聘'
ELSE '其它' END) as sta
from recruitment
) as re_statue,
recruitment rec
where
rec.id = re_statue.id
and re_statue.sta like '%未%'
其中WHEN後面爲條件,THEN後面爲當數據爲此時的結果。ELSE是超出以上條件的默認值。
另一種寫法
select rec.status rec_status,re_statue.sta from
(select id,
(CASE status WHEN 0
THEN '未領取 '
WHEN 1
THEN '招聘中 '
WHEN 2
THEN '招聘名額未滿'
WHEN 3
THEN '完成招聘'
ELSE '其它' END) as sta
from recruitment) as re_statue,
recruitment rec
where
rec.id = re_statue.id
and re_statue.sta like '%完成%'
可見兩種方式結果是相同的