假设我们有一个表 items
,其中包含列 name
和 attributes
:
CREATE TABLE students (
name VARCHAR(100),
attributes JSON
)
其中 attributes 是一组(总是结构相同的)JSON 文档,例如
[{"name":"Attribute 1","value":"Value 1"},{"name":"Attribute 2","value":"Value 2"}]
我现在想找到任何属性值匹配某项(例如 Foo%
)的所有学生。 Here's a playground example .
我意识到这并不是最直接的设计,但就目前而言,这是我必须使用的设计,尽管这种搜索的性能绝对非常低效当然是一个有效的问题。
最佳答案
您可以使用 json_array_elements
访问元素,然后使用 ->> json 运算符使用某个值进行搜索。
select s.*,j from
students s
cross join lateral json_array_elements ( attributes ) as j
WHERE j->>'value' like 'Foo%'
编辑
The problem here now is that the cross join will "duplicate" rows. Is there a better way to avoid this
使用 WITH ORDINALITY
为每个元素生成 id,然后使用 DISTINCT ON
获取每个学生的第一个/最后一个匹配项。
select DISTINCT ON (name) s.*,j.attr from
students s
cross join lateral json_array_elements ( attributes ) WITH ORDINALITY as j(attr,id)
WHERE j.attr->>'value' like 'Value%'
ORDER BY name,j.id
关于sql - postgresql:在 JSON 数组中过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53591359/