2

我有一个以列命名的表departments-

id number(10)
description varchar2(20)

filters还有一个名为列的配置表-

filtername varchar2(10)
filter varchar2(20)

filter列应包含应在子句中用作过滤器的 id 列表,where例如“10,20,30”

select * 
 from departments
    , filters 
where filters.filtername='MYFILTE' 
  and departments in filters.filter

每个过滤器只能使用一条记录。这可能吗 ?

4

2 回答 2

2
select * 
 from departments d 
where id in (select regexp_substr(filter,'[^,]+', 1, level) from filters
               where filtername='MYFILTE' --use this line if you only want to use one filter, remove if you want to apply all filters
             connect by regexp_substr(filter, '[^,]+', 1, level) is not null);

像这样的表——

create table filters (filter varchar2(100), filtername varchar2(20));

有了这样的数据——

insert into filters values ('10,20,30','Filter1');
insert into filters values ('40,50,60','Filter2');

像这样运行查询(假设列filter的值由 分隔,)-

select distinct regexp_substr(filter,'[^,]+', 1, level) from filters
connect by regexp_substr(filter, '[^,]+', 1, level) is not null
order by 1;

返回这个-

REGEXP_SUBSTR(FILTER,'[^,]+',1,LEVEL)
-----------------------------------------
10
20
30
40
50
60 

注意 - 与您的情况distinct无关order by(即在您的查询中不需要,但您仍然可以使用它们)。

于 2012-09-11T19:39:43.040 回答
0

这是通过一个简单的连接实现的:)

select * 
from departments d
join filters f on d.description = f.filter
where f.filtername='MYFILTE' 

编辑:我错过了 f.filter 是带有值的逗号分隔字符串在这种情况下,有两个选项:

使用喜欢:

select * 
from departments d
join filters f on f.filter like '%'||d.description||'%'
where f.filtername='MYFILTE' 

或使用您自己的爆炸功能:

CREATE OR REPLACE TYPE DM.varchar_list_type as table of varchar2(255);

CREATE OR REPLACE function explode(p_separator in varchar2, p_string in varchar2)
return varchar_list_type 
as
   l_string   varchar2(4000) default p_string || p_separator;
   l_data     varchar_list_type := varchar_list_type();
   n          number;
begin
   loop
      exit when l_string is null;
      n := instr (l_string, p_separator);
      l_data.extend;
      l_data (l_data.count) := ltrim (rtrim (substr (l_string, 1, n - 1)));
      l_string := substr (l_string, n + 1);
   end loop;

   return l_data;
-- no exception. I want to see the error messages (for now at least)
end;

select * 
from departments d
join filters f on d.description in (table(explode(',', f.filter)))
where f.filtername='MYFILTE' 
于 2012-09-11T21:32:12.237 回答