简体   繁体   English

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

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

I am trying to write an Oracle 12c SQL statement like this: 我正在尝试编写如下的Oracle 12c SQL语句:

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

I want the dynamic value to be the result of the following SQL: 我希望动态值是以下SQL的结果:

select col2 from table2 where rowid = 1

Is this possible? 这可能吗? Col2 contains a list of values like this: 'val1','val2','val3' Col2包含一个类似这样的值的列表:'val1','val2','val3'

Thank you 谢谢

Instead of dynamic-sql, you can split the string and perform the query. 您可以拆分字符串并执行查询,而不是dynamic-sql。 To split the string use regexp_substr . 要分割字符串,请使用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)

Why not just do this? 为什么不这样做呢?

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

EDIT: 编辑:

Storing lists of values in a single column is such a bad idea that I interpreted the question incorrectly. 在单列中存储值列表是一个坏主意,以至于我错误地解释了这个问题。 I took the "list of values" to be the values stored in different rows. 我将“值列表”作为存储在不同行中的值。 Why? 为什么? Because that is the right way to store the data. 因为那是存储数据的正确方法。 It is not SQLish to store lists of columns in a delimited list. 将列的列表存储在带分隔符的列表中不是SQLish。

That said, we are sometimes stuck with other people's really bad design decisions. 就是说,有时我们会陷入别人的错误设计决定中。 You can use a query such as this, if you are in this situation: 如果您处于这种情况,则可以使用这样的查询:

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