Home > Database > Mysql Tutorial > body text

MySQL中使用case when 语句实现多条件查询的方法

WBOY
Release: 2016-06-07 18:03:09
Original
3565 people have browsed it

今天在一个应用中使用到了一个比较特殊的数据查询要求。需要的朋友可以参考下。

举例如下:

数据表为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
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template