sql - postgresql:在 JSON 数组中过滤

标签 sql postgresql

假设我们有一个表 items,其中包含列 nameattributes:

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%'

Demo

编辑

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

Demo2

关于sql - postgresql:在 JSON 数组中过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53591359/

相关文章:

ruby-on-rails - 没有经验的 Rails 用户 : Wanting to Connect PostgreSQL to Already Existing App: Server Will not Connect

python - 将一个键值从字典列表转换为列表

postgresql - 数据库操作预期影响 1 行但实际上影响了 0 行与 Entity Framework

mysql - 用于链接图的 NoSQL 或 SQL

mysql - 什么时候同时使用外键作为主键?

sql - Rails 3 update_all 使用已包含在每个记录中的表中的数据

python - pip 安装 psycopg2 不工作

java - 如何使用注释@Test(expected = PSQLException.class) 在 Junit 4.12 PSQLException 中进行测试

mysql - 如何导入dbf文件数据到phpMyAdmin(Mysql服务器)

python pandas to_sql 与 sqlalchemy : how to speed up exporting to MS SQL?