简体   繁体   English

在where子句中如何获得多个条件

[英]How to get multiple conditions in case in where clause

I want to run a query on some fields of the table, but I cant understand how to do it. 我想在表的某些字段上运行查询,但是我不明白该怎么做。 I have the condition that first I need to check value of col1 , if it is 'W', then I need to check colA having values in ('1','2'), if it is not 'W', then I need to check colB having values in ('1','2'). 我的条件是,首先我需要检查col1的值,如果它是'W',那么我需要检查colA在('1','2')中的值,如果它不是'W',那么我需要检查值('1','2')中的colB This condition to check ('1','2') applies same to both colA and colB, just depending on the value of col1. 仅根据col1的值,此检查条件('1','2')应用于colA和colB。

I tried using this, but obviously this is incorrect. 我尝试使用它,但是显然这是不正确的。

SELECT * FROM tbl
WHERE CASE WHEN col1= 'W' THEN (colA IN ('1','2')) ELSE (colB IN ('1','2')) END

So how can I do it in a single query without using Unions etc. 因此,如何在不使用工会等的情况下通过单个查询进行操作。

You don't need CASE , just put all your boolean logic together in one expression. 您不需要CASE ,只需将所有布尔逻辑放在一个表达式中即可。

SELECT *
FROM T
WHERE
    (Col1 = 'W' AND ColA IN ('1', '2'))
    OR
    (Col1 <> 'W' AND ColB IN ('1', '2'))
;

在此处输入图片说明 Sql Server-2014 : Use CASE to choose column to be used in WHERE clause based on condition- SQL Server-2014:使用CASE根据条件选择要在WHERE子句中使用的列

SELECT * FROM tab1 
WHERE 
    (CASE WHEN col1= 'W' THEN colA ELSE colB END) in ('1', '2');

Tested on SqlServer-2014 . 在SqlServer-2014上测试 image attached 附加图片

MySql : Use IF() function to choose column to be used in WHERE clause based on condition- MySql:使用IF()函数根据条件选择要在WHERE子句中使用的列

SELECT * FROM tab1 
WHERE 
    IF(col1='W', colA, colB) in ('1', '2');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM