简体   繁体   English

SQL或在WHEN中(在CASE中)

[英]SQL OR within WHEN (in CASE)

Strangely i could not find this on the web, I need an OR within a when clause in a case statement, something like: 奇怪的是我在网上找不到这个,我需要在case语句中的when子句中使用OR,例如:

SELECT type,color,brand,CASE type WHEN "foo" OR "BAR" OR "somethingelse" THEN SELECT ... FROM .... WHERE .... > ....;

I just cant find a way to make it work, i have tried enclosing it in parenthesys: 我只是找不到让它工作的方法,我已经尝试将其封装在parenthesys中:

SELECT type,color,brand,CASE type WHEN ("foo" OR "BAR" OR "somethingelse") THEN SELECT ... FROM .... WHERE .... > ....;

Or in square brackets: 或者在方括号中:

SELECT type,color,brand,CASE type WHEN ["foo" OR "BAR" OR "somethingelse"] THEN SELECT ... FROM .... WHERE .... > ....;

The problem is that i have more groups of options to check, and make a single WHEN for each of them, will make my query super long. 问题是我有更多的选项要检查,并为每个选项制作一个WHEN,这将使我的查询超长。 Nothing, any advice? 没什么,有什么建议吗?

In CASE you cannot start a separate SELECT without brackets ... and the OR is possible with the following: CASE如果没有括号,则无法启动单独的SELECT ...并且可以使用以下内容进行OR

CASE WHEN type IN ("foo","BAR","somethingelse") THEN ... ELSE END

If you want to get the target value from a select call (subquery) then do this in the THEN section 如果要从select调用(子查询)中获取目标值,请在THEN部分中执行此操作

... THEN ( SELECT col1 FROM tble WHERE ... ) ELSE END

case has two forms Only one can use Or case有两种形式只有一种可以使用Or

  1. case x when val1 then result1 when val2 then result2 else defaultResult end
  2. case when x = val1 then result1 When y = val2 then result2 Else DefaultResult end , or, more generally: case when x = val1 then result1 When y = val2 then result2 Else DefaultResult end ,或更一般地说:
    case when [boolExp1] then reslt1 when [boolExp2] then reslt2 else defltReslt end

the second form can use Or , or any other Boolean operator for that matter (except Exists as I recall) 第二种形式可以使用Or或任何其他布尔运算符(我记得Exists除外)

 case when x = val1 or y = val2 or z in (val3, val4, val5) then result1 
      else defaultResult end

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

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