我有一个名为departments
的表格,其中包含列 -
id number(10)
description varchar2(20)
一个名为filters
的配置表,其中包含列 -
filtername varchar2(10)
filter varchar2(20)
filter
列应包含应在where
子句中用作过滤器的ID列表,例如'10,20,30'
select *
from departments
, filters
where filters.filtername='MYFILTE'
and departments in filters.filter
我每个过滤器只能使用一条记录。这可能吗 ?
答案 0 :(得分: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
都不重要(即您的查询中不需要,但无论如何都可以使用它们。)
答案 1 :(得分:0)
这是通过简单的连接来实现的:)
select *
from departments d
join filters f on d.description = f.filter
where f.filtername='MYFILTE'
编辑:我错过了f.filter是一个逗号分隔的字符串,带有值 在这种情况下,有两个选项:
使用LIKE:
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'