Oracle 12c - 根据不同 table 中的值动态生成 where 子句

Oracle 12c - dynamically generate a where clause based on a value in a different table

我正在尝试像这样编写 Oracle 12c SQL 语句:

select * from table1 where col1 in (*dynamicvalue*)

我希望动态值是以下 SQL 的结果:

select col2 from table2 where rowid = 1

这可能吗? Col2 包含这样的值列表:'val1'、'val2'、'val3'

谢谢

为什么不这样做呢?

select t1.*
from table1 t1
where t1.col1 in (select col2 from table2 where rowid = 1);

编辑:

在单个列中存储值列表是个糟糕的主意,以至于我错误地解释了这个问题。我将 "list of values" 作为存储在 different 行中的值。为什么?因为那是存储数据的正确方法。在分隔列表中存储列列表不是 SQLish。

也就是说,我们有时会受制于其他人非常糟糕的设计决策。如果您处于这种情况,您可以使用这样的查询:

select t1.*
from table1 t1
where exists (select 1
              from table2 t2
              where rowid = 1 and
                    ',' || t2.col2 || ',' like '%,' || t1.col1 || ',%'
             );

而不是动态-sql,您可以拆分字符串并执行查询。要拆分字符串,请使用 regexp_substr.

select * from table1 
where col1 in (select regexp_substr(col2,'[^,]+', 1, level)  
               from table2
               connect by regexp_substr(col2, '[^,]+', 1, level) is not null)