CASE WHEN的簡單用法

  最近在做項目時遇到一個問題,要對一些條件進行模糊查詢,但數據庫中保存的是數字,找了一些方法,感覺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 '%完成%'

這裏寫圖片描述

可見兩種方式結果是相同的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章