【问题标题】:Postgresql: Filter array by seriesPostgresql:按系列过滤数组
【发布时间】:2021-02-04 23:29:47
【问题描述】:

有没有办法按系列过滤和排列列? 用一个例子来解释更简单。 想象一下我有这些数据:

table: data
id   tag
1    {a,b,c,d}
2    {a,c,d,b}
3    {c,d,a,b}
4    {d,c,b,a}
5    {d,a,b,c}
6    {d,a,c,b}

现在我想获取所有行,其中包含 ["a", "b"] 的顺序,并且中间没有项目:

SELECT id from data where tags ???? ["a", "b"]

该查询应返回:1,3,5

更新 1: 看了array_positionarray_positionS之后:https://www.postgresql.org/docs/10/functions-array.html

我写了这个查询:

select id
from data 
where 'a' = ANY(tags)
    and 'b' = ANY(tags) 
    and (array_position(tags, 'a') + 1) = any(array_positions(tags, 'b' ))

按预期工作

更新 2:

正如@klin 评论,如果'a' 可以出现多次,这将产生错误的结果,例如{a,a,b,c,d}。所以这是一个更通用的答案

select *
from data
where 'a' = any(tags)
and 'b' = any(tags) 
and (
    array_position(tags, 'a') + 1 = any(array_positions(tags, 'b' ))
    or array_position(tags, 'b') - 1 = any(array_positions(tags, 'a' )))

【问题讨论】:

    标签: arrays postgresql filter


    【解决方案1】:

    您可以在数组的文本表示上使用a regular expression

    select *
    from my_table
    where tag::text ~ '[\{,]a,b[,\}]'
    

    Db<>Fiddle.

    【讨论】:

    • 感谢您的帮助。看看更新,你认为哪个查询会有更好的性能?
    • 我回到了这个问题,因为您的解决方案对我来说似乎太简单了。事实上,查询在某些情况下可能会给出意想不到的结果:Db<>fiddle.
    • 嗨@klin 感谢您的额外努力。确实你是对的,经过一些测试,我得出了同样的结论。但是,我在问题中显示的数据只是一个例子。真实数据上a不能重复,而b可以。我应该对原始问题发表评论。
    猜你喜欢
    • 2021-11-26
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多