MySQL中使用case when 语句实现多条件查询的方法
程序员文章站
2023-12-17 09:16:34
举例如下: 数据表为demotable,字段有id, condition1,condition2,condition3,condition4,condition5 要求是查...
举例如下:
数据表为demotable,字段有id, condition1,condition2,condition3,condition4,condition5
要求是查询demotable中,condition1,condition2,condition3,condition4,condition5五个字段中符合任意两个或两个以上的条件的内容。
可使用case when来实现这个条件,需要嵌套子查询语句
sql语句代码示例如下:
select * from demotable
where ((select case 1 when condition1满足条件 then 1 else 0 end from demotable )
+(select case 1 when condition2满足条件 then 1 else 0 end from demotable)
+(select case 1 when condition3满足条件 then 1 else 0 end from demotable)
+(select case 1 when condition4满足条件 then 1 else 0 end from demotable)
+(select case 1 when condition5满足条件 then 1 else 0 end from demotable))>=2
数据表为demotable,字段有id, condition1,condition2,condition3,condition4,condition5
要求是查询demotable中,condition1,condition2,condition3,condition4,condition5五个字段中符合任意两个或两个以上的条件的内容。
可使用case when来实现这个条件,需要嵌套子查询语句
sql语句代码示例如下:
复制代码 代码如下:
select * from demotable
where ((select case 1 when condition1满足条件 then 1 else 0 end from demotable )
+(select case 1 when condition2满足条件 then 1 else 0 end from demotable)
+(select case 1 when condition3满足条件 then 1 else 0 end from demotable)
+(select case 1 when condition4满足条件 then 1 else 0 end from demotable)
+(select case 1 when condition5满足条件 then 1 else 0 end from demotable))>=2