javascript - Sequelize/postgres : Get records matching a value inside an array of object with a provided value

标签 javascript json postgresql select sequelize.js

我有一个存储对象数组的 db 列。一个示例值是:

[{
  "recordId": 11,
  "column": [{
      "name": "some value",
      "id": "1"
    },
    {
      "name": "other value",
      "id": "2"
    }
  ]
}, {
  "recordId": 12,
  "column": [{
      "name": "some value",
      "id": "3"
    },
    {
      "name": "other value",
      "id": "4"
    }
  ]
}]

现在,如果我想通过 sequelize 搜索具有 id:1 的记录,那么 where 子句中应该包含哪些内容,或者还有其他方法吗?

最佳答案

您正在寻找 json 数组至少有一个对象的行,该对象的 id 属性值为 1 。在纯 SQL 中,您可以将 exists 与取消嵌套数组的相关子查询一起使用:

select t.*
from mytable t
where exists (
    select 1
    from jsonb_array_elements(t.column) as x(obj)
    where (x.obj ->> 'id')::int = 1
)

关于javascript - Sequelize/postgres : Get records matching a value inside an array of object with a provided value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62345734/

相关文章:

json - 尝试在 golang 1.12 中解码 json 字节数组

postgresql - 如何将数据从 FileMaker Pro 导入到 PostgreSQL

PostgreSQL 大表 SELECT/INSERT 性能?

sql - Postgresql COPY命令导出数据到csv : Can we achieve double quotes for strings in csv's?

被拖动项目的 jQuery Id

javascript - 停止在滚动时淡入后出现 div

javascript - jquery div扩展背景颜色不透明度变化

json - 带有接受 header application/json 的 REST API 返回一个数字

java - 在列表的序列化中包含具有数组索引的字段

javascript - 如何返回两个包含字符串的数组之间的差异