一.模拟场景
你需要关联两个表,其中t1是数据表,t2是维护表.
我们希望,维护表的name列的后缀不为 “测试” 的时候,t1.a=t2.b,当为 “测试” 的时候,t1.a>t2.b
/*思路大概是这个样子,但 case when 函数不可以这样操作*/
and (case when t2.name like '%测试' then t1.a > t2.b else t1.a = t2.b end)
/*换思路,但 case when 函数依旧不可以这样操作*/
and t1.a(case when t2.name like '%测试' then > else = end)t2.b
/*换思路,但 case when 函数依旧不可以这样操作*/
and t1.a(case when t2.name like '%测试' then '>' else '=' end)t2.b
二.解
效果:
and ((t1.a = t2.b and 1=(case when t2.name like '%测试' then 0 else 1 end))
or(t1.a > t2.b and 1=(case when t2.name like '%测试' then 1 else 0 end)))
三.思路
先将两个限制都加进去:
and ((t1.a = t2.b and 1=1 ) or (t1.a > t2.b and 1=1))
这样相当于抓取了大于等于的数据,因为 "case when"函数只支持输出一个值,且不能为运算字符,所以我们通过改变 “1=1” 来做出限制,及2.效果所展示的sql语句