简体   繁体   English

具有嵌套多个条件的 WHERE 子句

[英]WHERE clause with nested multiple conditions

I want to retrieve data with conditions in WHERE clause.我想用WHERE子句中的条件检索数据。
Here is my table something look like:这是我的表格,如下所示:

Name   Location    Age
----------------------
AAA     Bhuj       24
BBB     Mumbai     22
CCC     Bhuj       18
DDD     Bhuj       27
EEE     Mumbai     26

My condition in WHERE clause is:我在WHERE子句中的条件是:
if location = 'Bhuj' then Age>20 else if location = 'Mumbai' then Age>25

I am trying this code to achieve this:我正在尝试这段代码来实现这一点:

SELECT * FROM testing
WHERE 
CASE Location WHEN 'Bhuj' THEN Age>20
              WHEN 'Mumbai' THEN Age>25
END;

This code works fine for MySQL ( see this SQLFiddle ) but does not work for SQL Server ( see this SQLFiddle ) and giving the following error:此代码适用于 MySQL(请参阅此 SQLFiddle ),但不适用于 SQL Server(请参阅此 SQLFiddle )并给出以下错误:

Incorrect syntax near '>'.: SELECT * FROM testing WHERE case Location When 'Bhuj' then Age>20 When 'Mumbai' then Age>25 end '>' 附近的语法不正确。:SELECT * FROM testing WHERE case Location When 'Bhuj' then Age>20 When 'Mumbai' then Age>25 end

Any suggestion?有什么建议吗?

I think this is what you're trying to achieve我认为这就是您要实现的目标

   SELECT * 
   FROM testing
   WHERE (Location = 'Bhuj' AND Age>20) 
        OR (Location = 'Mumbai' AND Age>25)

Check SQLFiddle检查SQLFiddle

UPDATE:更新:

Case statement returns a value, you can't have a condition inside it. Case 语句返回一个值,其中不能有条件。

SELECT * FROM testing 
WHERE  
Age > case Location When 'Bhuj' then 20 
              When 'Mumbai' then 25 
              end

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

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