【发布时间】: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_position和array_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