oracle-how use string data in(in运算符)

r8uurelv  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(267)

在tbl\ 1中,我有:

id
1
2
3
4
5
6
7
8
9

in tbl_2:
id  value
1   1,2,3
2   5

选择from tbl\u 1 where id in(选择值from tbl\u 2 where id=2)--可以
选择
from tbl\u 1 where id in(选择值from tbl\u 2 where id=1);

--Need this resault: 3 rows:  1, 2 and 3
5f0d552i

5f0d552i1#

还有一个选择:

SQL> with
  2  -- sample data
  3  tbl_1 (id) as
  4    (select 1 from dual union all
  5     select 2 from dual union all
  6     select 3 from dual union all
  7     select 4 from dual union all
  8     select 5 from dual union all
  9     select 6 from dual union all
 10     select 7 from dual union all
 11     select 8 from dual union all
 12     select 9 from dual
 13    ),
 14  tbl_2 (id, value) as
 15    (select 1, '1,2,3' from dual union all
 16     select 2, '5,6,7' from dual
 17    )
 18  -- query which returns what you want
 19  select a.id
 20  from tbl_1 a join
 21    (select regexp_substr(b.value, '[^,]+', 1, column_value) id
 22     from tbl_2 b cross join
 23       table(cast(multiset(select level from dual
 24                           connect by level <= regexp_count(b.value, ',') + 1
 25                          ) as sys.odcinumberlist))
 26     where b.id = 1
 27    ) c on c.id = a.id;

        ID
----------
         1
         2
         3

SQL>
d4so4syb

d4so4syb2#

修正你的数据模型!不应将数字存储为字符串。您应该正确声明了外键关系。字符串不应用于存储多个值。
有时候,我们会被别人的错误决定所困扰。你可以用“比如:

Select t1.*
from tbl_1 t1
where exists (select 1
              from tbl_2 t2
              where t2.id = 1 and
                    ',' || t2.value || ',' like '%,' || t1.id ',%'
             );

但是,您应该努力修复数据,而不是试图处理它。正确的数据应该是每行一个的连接/关联表 id 以及 value 对于表2:

id  value
1   1
1   2
1   3
2   5
shstlldc

shstlldc3#

一个选项使用字符串函数:

select t1.*
from t1
inner join t2 on ',' || t2.value || ',' like '%,' || t1.id || ',%'
where t2.id = 1

相关问题