1. 程式人生 > >mysql中使用case when 做where條件篩選表記錄

mysql中使用case when 做where條件篩選表記錄

平時我們專案中經常用到 where  欄位名=值  來篩選查詢結果,但實際也會遇到這樣的情況,如果表中某個欄位code的值是“_1”結尾的,那麼就查全部,否則,根據輸入的引數查詢。

這時 case when 就派上用途了:

select * from table_name  t

where t.status='1' and 

(case when instr(right(t.code,2),'_1') > 0 then 1=1

when instr(right(t.code,2),'_1') = 0 then t.name=#{param.name}

end)

and .....

當然,最多的時候一般是使用case when 來作為查詢結果的處理

select  t.id,t.name,

( case when t.sex='1' then '男' else '女‘ end ) sex

轉載:https://blog.csdn.net/yansong_8686/article/details/47459507