我有以下查询:
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.a
是aa
或bb
,如果t1.e = t2.e
返回true,我必须只选择行。现在,如果t1.a
是cc
或dd
,那么它必须只选择t1.e = t2.f
行,比较不同的列。没有程序可以做到吗?
如果您确实想要修复错误,请将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;
为什么case
呢?您可以生成简单的布尔输出,它们可以直接使用。
where
...
and ((t1.a in ('aa', 'bb') and t1.e = t2.e) or
(t1.a in ('cc', 'dd') and t1.e = t2.f)
)
写这个的正确方法是使用正确的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) )
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'
祝你好运。