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



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

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

下面是结果集的示例:

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

我希望结果是

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

试试这个:

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

您可以尝试全文搜索,但 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

最新更新