sql - 查询 JSON 列中的数组元素

最近升级到使用 PostgreSQL 9.3.1 以利用 JSON 功能。在我的表中,我有一个 json 类型的列,其结构如下:

{
   "id": "123",
   "name": "foo",
   "emails":[
      {
        "id": "123",
        "address": "somethinghere"
      },
      {
        "id": "456",
        "address": "soemthing"
      }
   ]
} 

这只是用于问题目的的虚拟数据。

是否可以根据 id 查询 emails 数组中的特定项目?
差不多:“return email where id=123)”?

最佳答案

对于 Postgres 9.4+,请参阅 adamc 稍后的回答。或者:

  • Query for array elements inside JSON type

Postgres 9.3 的原始答案

是的,这是可能的:

SELECT *
FROM   tbl t, json_array_elements(t.json_col->'emails') AS elem
WHERE  elem->>'id' = 123;

tbl 是您的表名,json_col 是 JSON 列的名称。

另见:

  • How do I query using fields inside the new PostgreSQL JSON datatype?

关于隐式CROSS JOIN LATERAL:

  • PostgreSQL unnest() with element number

支持这种查询的索引:

  • Index for finding an element in a JSON array

https://stackoverflow.com/questions/19568123/

相关文章:

json - Node 事件.js :167 throw er;//Unhandled 'error

json - Spring MVC - JSON 无限递归

iphone - 减去两个 NSDate 对象

ruby-on-rails - rails jbuilder - 只是一个字符串数组

ajax - django:使用 json 对象测试基于 POST 的 View

json - 如何检查 Postgres 中是否存在 json 键?

jquery - 使用 JSON 将嵌套对象发布到 Spring MVC Controller

jquery - 来源http ://localhost is not allowed by Acc

java - 使用 JSONObject 在 Java 中为以下结构创建嵌套 JSON 对象?

javascript - 将 JSON 数据从 php 传递给 html-data 属性,然后传递给