Oracle' where子句'变得更短

时间:2016-08-09 20:57:10

标签: sql oracle

让我们假设' table1'有三列:

'键&#39 ;, ' singleID&#39 ;, ' multipleIDs'

行会像:

1,'8736', '1234;6754;9785;6749' 
2,'7446', '9959;7758;6485;9264'

要搜索所有在' singleID'或作为的一部分 ' multipleIDs'中的连接ID我会:

select key from table1 where 
  singleID = '8888' or multipleIDs like '%8888%';

当不仅搜索此语句中的一个ID(8888)而且搜索100时,有必要使用不同的id重复where子句100次,如:

select key from table1 where 
  singleID = '8888' or multipleIDs like '%8888%' or
  singleID = '9999' or multipleIDs like '%9999%' or
....;

要搜索的ID是从其他查询(如

)动态获取的
 select id from table2;

查询应该 由于ID的数量可能不同,因此可以动态创建。 像这样,SQL语句会变得很长。

在Oracle SQL中有没有一种很好的简短方法来表达它? PLSQL也许?

2 个答案:

答案 0 :(得分:0)

这样的东西?

这是测试版本:

with sv_qry
as
(
SELECT trim(regexp_substr(search_values, '[^,]+', 1, LEVEL)) val
  FROM (select '1234,7446' as search_values
from dual
)
CONNECT BY LEVEL <= regexp_count(search_values, ',')+1
)
, table1_qry
as
(select 1 as id,'8736' as single_id, '1234;6754;9785;6749' as multiple_id from dual
union all
select 2,'7446' as single_id, '9959;7758;6485;9264' as multiple_id from dual
)
select *
from table1_qry
inner join
sv_qry
on  single_id = val or multiple_id like '%'||val||'%'

这将是一个名为table1的表:

with sv_qry
as
(
SELECT trim(regexp_substr(search_values, '[^,]+', 1, LEVEL)) val
  FROM (select '1234,7446' as search_values
from dual
)
CONNECT BY LEVEL <= regexp_count(search_values, ',')+1
)
select *
from table1
inner join
sv_qry
on  single_id = val or multiple_id like '%'||val||'%'

部分功劳归于此:

Splitting string into multiple rows in Oracle

答案 1 :(得分:0)

您可以像这样表达查询:

  select key
    from table1 a
    join ( select id from table2 where id in ('yyyy','xxxx','zzzz',...) b 
    on a.singleId = b.id or a.multipleID like '%'||b.id||'%';