Oracle SQL:仅返回另一个表中字段中包含的值

时间:2013-02-23 20:19:34

标签: sql string oracle subquery

我正在尝试编写一个Oracle SQL查询,以返回一组当前配置为执行作业的值。

我有两张桌子:

VALUES
A
B
C
D


JOB, STRINGS_TO_SEARCH
1    {r, e, 'Hello' A w: B, xyz}
2    {ok, D }

每个作业的配置存储在一个字符串中。我如何编写一个只返回为作业配置的值的查询?

使用内置的Oracle功能是否可以实现?好像我可能要求生成动态查询...

1 个答案:

答案 0 :(得分:0)

create table T_VALUES (
   VAL   varchar2(20)
);

insert into T_VALUES values ('A');
insert into T_VALUES values ('B');
insert into T_VALUES values ('C');
insert into T_VALUES values ('D');

create table T_JOBS (
   JOB_ID   int,
   STR_LIST varchar2(50)
);

insert into T_JOBS values (1, 'r, e, ''Hello'' A w: B, xyz');
insert into T_JOBS values (2, 'ok, D ');

select
   job_id,
   val
from
   T_VALUES
   natural join (
      select
         job_id,
         regexp_substr(str_list, '[^ ,]+', 1, occ) as val
      from
         T_JOBS
         cross join (
            select level as occ from dual
            connect by level <= (select max(length(str_list)) from T_JOBS)
         )
   )
order by 1, 2

fiddle


编辑:

改进版(使用Ben的想法)

create table T_VALUES (
   VAL   varchar2(20)
);

insert into T_VALUES values ('A');
insert into T_VALUES values ('B');
insert into T_VALUES values ('C');
insert into T_VALUES values ('D');

create table T_JOBS (
   JOB_ID   int,
   STR_LIST varchar2(50)
);

insert into T_JOBS values (1, 'junk, values=A:NotA:B:r:e, more_junk');
insert into T_JOBS values (2, 'ok, values=D ');

create type nt_str as table of varchar2(50);

select
   j.job_id,
   v.val
from
   T_JOBS j,
   table(
      cast(
        multiset(
          select
            regexp_substr(
              regexp_substr(j.str_list, 'values=([^, ]+)', 1, 1, 'i', 1), 
              '[^:]+', 1, level)
          from dual
          connect by 
            regexp_substr(
              regexp_substr(j.str_list, 'values=([^, ]+)', 1, 1, 'i', 1), 
              '[^:]+', 1, level) is not null
        ) as nt_str
      )
   ) t
   join T_VALUES v 
     on v.val = t.column_value
order by 1, 2

one more fiddle