如何用条件更改WHERE子句?

问题描述 投票:0回答:4

我有以下查询:

select t1.a,
       t1.b,
       t2.c,
       ....
  from table1 t1,
       table2 t2,
       ...
 where ...
   and condition1
   and condition2
   and
  case
     when (t1.a in ('aa', 'bb') and
          t1.e = t2.e) then
      true
     when (t1.a in ('cc', 'dd') and
          t1.e = t2.f) then
      true
     else
      false
   end;

我想确定使用列值的where子句。上面的查询在最后一行返回ORA-00920 invalid relational operator。我检查了here以调整我的条款。如果t1.aaabb,如果t1.e = t2.e返回true,我必须只选择行。现在,如果t1.accdd,那么它必须只选择t1.e = t2.f行,比较不同的列。没有程序可以做到吗?

sql oracle
4个回答
2
投票

如果您确实想要修复错误,请将true更改为1,将false更改为0,然后将其等同为1. Case语句就像一个函数,并且需要一个表达式(如= 1)。

and
  (case
     when (t1.a in ('aa', 'bb') and
          t1.e = t2.e) then
      1
     when (t1.a in ('cc', 'dd') and
          t1.e = t2.f) then
      1
     else
      0
   end) = 1;

7
投票

为什么case呢?您可以生成简单的布尔输出,它们可以直接使用。

where
   ...
   and ((t1.a in ('aa', 'bb') and t1.e = t2.e) or
        (t1.a in ('cc', 'dd') and t1.e = t2.f)
   )

2
投票

写这个的正确方法是使用正确的join语法。切勿在FROM子句中使用逗号:

from table1 t1 join
     table2 t2
     on (t1.a in ('aa', 'bb') and t1.e = t2.e) or
        (t1.a in ('cc', 'dd') and t1.e = t2.f)

或者,因为Oracle支持元组:

from table1 t1 join
     table2 t2
     on (t1.a, t1.e) in ( ('aa', t2.e), ('bb', t2.e), ('cc', t2.f), ('dd', t2.f) )

1
投票

Oracle数据库不支持布尔值。它们在PL / SQL中可用,但数据库产品本身缺少布尔值,因此您不能在查询中使用诸如TRUE和FALSE之类的值。因此,通常使用字符串值“Y”和“N”或“t”和“f”来表示布尔结果。我建议将您的查询重写为:

select t1.a,
       t1.b,
       t2.c,
       ....
  from table1 t1,
       table2 t2,
       ...
 where ...
   and condition1
   and condition2
   and case
         when (t1.a in ('aa', 'bb') and
              t1.e = t2.e)
           then 'Y'
         when (t1.a in ('cc', 'dd') and
              t1.e = t2.f)
           then 'Y'
         else 'N'
       end = 'Y'

祝你好运。

© www.soinside.com 2019 - 2024. All rights reserved.