带有case语句的Oracle sql join

时间:2017-09-06 18:16:34

标签: sql oracle join

我有两个表,连接条件必须依赖于第二个表的某个值。在下面的sql中,该行是我正在尝试实现的连接条件,但它会抛出编译错误,不知道如何执行此操作。

注意:这是一个大查询的一部分,加入将是有效的方法。

投掷线编译错误

data.hasIndicator in (case when prim.ind = 'YES' then 'YES' when prim.ind = 'NO' then ('YES','NO') end)

- 完整sql

with data as
  (select
     'YES' hasIndicator, 'Gold' item, 12 itemId
   from dual
   union
   select
     'YES' hasIndicator, 'Silver' item, 13 itemId
   from dual
   union
   select
     'NO' hasIndicator, 'Platinum' item, 14 itemId
   from dual),
prim as
  (select
     'NO' ind, 1 id
   from dual
   union
   select
     'YES' ind, 2 id
   from dual)
select *
from prim
  join data on
    data.hasIndicator in (case when prim.ind = 'YES' then ('YES') when prim.ind = 'NO' then ('YES','NO') end)
where
  id = 1;

1 个答案:

答案 0 :(得分:2)

case不会返回列表。它返回一个值。您可以将逻辑编写为:

select *
from prim join
     data 
     on (prim.ind = 'YES' and data.hasIndicator = 'YES') or
        (prim.ind = 'NO' and data.hasIndicator IN ('YES', 'NO'))
where id = 1;

或者,你可以稍微简化一下

     on (prim.ind = data.hasIndicator) or (data.hasIndicator = 'YES')