arrays - 与 AND 类似的 Postgres

标签 arrays postgresql pattern-matching

有什么方法可以将这个 OR 表达式更改为 AND?

title SIMILAR TO '%(foo|bar)%'

现在返回标题中包含 foo 或 bar 的所有行。我将如何返回包含 foo 和 bar 但在此顺序中不是必需的行。

所以“foo bar”和“bar foo”和“foo bla bar”都是有效结果。但是“foo salad”不是

最佳答案

将简单的 likeall(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/

相关文章:

r - 在 R 中按模式对数据帧进行分组

pattern-matching - OCaml 模式与非常量匹配

javascript - 使用日期类型对数组进行排序

python - 构建 numpy 矩阵

java - 如何在java中将二维整数数组转换为图像?

ios - 使用 swift 从解析的 Json 中提取数据

ruby - 为什么这段代码比较慢?

java - HikariCP 连接池未关闭

SQL LEFT JOIN 清空左表列

Ruby Kernel::system,shell 命令中的否定模式未按预期工作