Oracle使用dynamic in子句选择查询

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

我有以下查询

    select * from table_1 
    where Conditions in 
         (select case when check_condition = 'Y' then 'Condition_1' 
                 else 'N/A' end as Check_condition 
          from table_2 
          WHERE id = 1122)

其中table_1包含Conditions列中的值,如下所示。 Condition_1,Condition_2

这很好,并返回结果。

我想在in子句中使用多个select语句,我按如下方式执行。

    select * from table_1
    where Conditions in (
         select ''''||
             (select case when check_condition = 'Y' then 'Condition_1' 
               else 'N/A' end as Check_condition 
               from table_2 
               WHERE id = 1122)||''''||','''||
                  (select case when check_condition = 'Y' then 'Condition_2'
                        else 'N/A' end as Check_condition 
                  from table_2 WHERE id = 1122)||''''
                 from dual
                )

内部查询(在in子句内)给出了正确的预期结果 -

'Condition_1','Condition_2' 

当我将其粘贴到父查询时,它可以正常工作并显示结果。

select * from table_1 where Conditions in ('Condition_1','Condition_2')

我的问题是,当我使用第二个查询时,它没有给出任何结果。我知道子查询将返回应与外部查询中的行匹配的结果。但它显示了我的空结果集。

我正在使用oracle 11g

任何人都可以帮助我..提前谢谢大家。

sql database oracle oracle11g
2个回答
4
投票

关于要求的问题有点不清楚。我认为你想要的只是在以下情况下从table1中选择记录:

  • 行匹配'Condition_1'或'Condition_2'
  • check_condition ='Y'
  • table2有一行,ID = 1122

从你的问题中不清楚check_condition是一个列还是一个变量,如果它是一个列所属的列。因此,这种解决方案可能是错误的,但它说明了原理。

select * from table1 t1
where t1.conditions in ('Condition_1','Condition_2')
and t1.check_condition = 'Y'
and exists
        ( select null from table2 t2
          where t2.id = 1122 )

如果这不能提供您需要的解决方案,请修改您的问题,以便说明您需要实施的业务逻辑,还包括相关的表格描述。


1
投票

您最终会将两个值传递给in子句,就像手动执行时一样:

select * from table_1 where Conditions in ('Condition_1','Condition_2')

您传递的是一个值,它是值的串联:

select * from table_1 where Conditions in ('''Condition_1'',''Condition_2''')

没有condition匹配连接值,所以你没有得到任何结果。你可以这样做:

select * from table_1 where Conditions in (
  select case when check_condition = 'Y' then 'Condition_1' else 'N/A' end
  from table_2 WHERE id = 1122
  union all
  select case when check_condition = 'Y' then 'Condition_2' else 'N/A' end
  from table_2 WHERE id = 1122
)

或者,如果我遵循你正在做的事情(这是值得怀疑的,因为我不确定我理解你的数据模型!):

select * from table_1 where check_condition != 'Y' or Conditions in (
  select 'Condition_1' from table_2 WHERE id = 1122
  union all
  select 'Condition_2' from table_2 WHERE id = 1122
)

看起来你应该能够通过连接更干净地完成这项工作,但我认为我们需要查看结构和示例数据以了解更多内容。

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