Postgres - 过滤掉单词但排除其他模式

时间:2014-02-11 18:57:39

标签: sql postgresql pattern-matching

我正在尝试提取like '%asian%'的行。但我遇到的问题包括caucasian

有人可以帮助我使用包含label like '%asian%'但不包括caucasian的模式吗?我主要是寻找一个优雅的解决方案。我已经有了一个解决方案,我在结果集中有一个包含'%asian%'的临时表,然后我用caucasian删除任何结果。它不优雅,所以我正在寻找一个更简单的解决方案。

以下是结果集的示例:

label
--------------------
WHITE/CAUCASIAN
Asian/Pacif Isl His
CAUCASIAN
ASIAN

我希望结果是

label
--------------------
Asian/Pacif Isl His
ASIAN

2 个答案:

答案 0 :(得分:1)

试试这个:

 WHERE label ilike '%asian%' and label not ilike '%caucasian%' ? 

source

答案 1 :(得分:1)

您可以尝试全文搜索,但是postgres的解析器会将a / b视为文件路径,因此在这种情况下无效。

Houari的回答很好但在大桌上会很慢。

试试这个:

--your table:

create table a (
  label text primary key
);

insert into a values 
('WHITE/CAUCASIAN'),
('Asian/Pacif Isl His'),
('CAUCASIAN'),
('ASIAN');

--a function to split your labels into text arrays (splits on forward slash or space):

create or replace function get_terms(text) returns text[] language sql as '
  select regexp_split_to_array(lower($1), ''[\/ ]'');
'

--create a functional index for fast lookup:
create index terms on a using gin (get_terms(label));

--find rows where there is an array overlap:
select * from a where get_terms(label) && array['asian'];

http://sqlfiddle.com/#!15/14407/8