繁体   English   中英

Oracle 12c-根据不同表中的值动态生成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'

谢谢

您可以拆分字符串并执行查询,而不是dynamic-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)

为什么不这样做呢?

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

编辑:

在单列中存储值列表是一个坏主意,以至于我错误地解释了这个问题。 我将“值列表”作为存储在不同行中的值。 为什么? 因为那是存储数据的正确方法。 将列的列表存储在带分隔符的列表中不是SQLish。

就是说,有时我们会陷入别人的错误设计决定中。 如果您处于这种情况,则可以使用这样的查询:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM