Home >Database >Mysql Tutorial >MySQL中使用case when 语句实现多条件查询的方法_MySQL
bitsCN.com
举例如下:
数据表为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
bitsCN.com