有什么方法可以将这个 OR 表达式更改为 AND?
title SIMILAR TO '%(foo|bar)%'
现在返回标题中包含 foo 或 bar 的所有行。我将如何返回包含 foo 和 bar 但在此顺序中不是必需的行。
所以“foo bar”和“bar foo”和“foo bla bar”都是有效结果。但是“foo salad”不是
最佳答案
将简单的 like
与 all(array[...])
一起使用:
with the_data(title) as (
values
('foo bar'),
('bar foo'),
('foo bla bar'),
('foo salad')
)
select *
from the_data
where title like all(array['%foo%', '%bar%']);
title
-------------
foo bar
bar foo
foo bla bar
(3 rows)
更新以回应评论。仅搜索整个单词的情况要复杂一些。你应该使用 regex_split_to_array()
并检查结果数组是否包含搜索词数组(使用 array operator @> ):
with the_data(title) as (
values
('Foo bar'),
('Bar foo'),
('foo bla bar'),
('foo salad'),
('foobar'),
('barfoo')
)
select *
from the_data
where regexp_split_to_array(lower(title), ' ') @> array['foo', 'bar'];
title
-------------
Foo bar
Bar foo
foo bla bar
(3 rows)
关于arrays - 与 AND 类似的 Postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40720576/