Sql 查询JSON列中数组的元素

Sql 查询JSON列中数组的元素,sql,json,postgresql,postgresql-9.3,lateral,Sql,Json,Postgresql,Postgresql 9.3,Lateral,最近升级到使用PostgreSQL 9.3.1来利用JSON功能。在我的表中,有一个json类型的列,其结构如下: { "id": "123", "name": "foo", "emails":[ { "id": "123", "address": "somethinghere" }, { "id": "456", "address": "soemthing" }

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

{
   "id": "123",
   "name": "foo",
   "emails":[
      {
        "id": "123",
        "address": "somethinghere"
      },
      {
        "id": "456",
        "address": "soemthing"
      }
   ]
} 
SELECT *
FROM   table_name, json_array_elements(json_column) AS data
WHERE  data->>'id' = 123;
这只是问题中的虚拟数据

是否可以根据id查询电子邮件数组中的特定项目?
差不多:“返回id=123的电子邮件”?

是的,这是可能的:

SELECT *
FROM   tbl t, json_array_elements(t.json_col->'emails') AS elem
WHERE  elem->>'id' = 123;
tbl
是您的表名,
json\u col
是json列的名称

更多详情请参见本相关答案:

有关此相关答案最后一段中的隐式横向连接的更多信息:

支持此类查询的索引:


您可以简单地执行以下操作:

SELECT * FROM table WHERE emails->>'id' = '123';
您似乎将id存储为字符串,如果它是整数,您可以这样做:

SELECT *  from table WHERE cast(emails->>'id' as integer ) = 123  ;
或者您可以获取id>10的所有行

SELECT *  from table WHERE cast(emails->>'id' as integer ) > 10  ;

看到这篇文章,发现您可以像这样直接查询表:

{
   "id": "123",
   "name": "foo",
   "emails":[
      {
        "id": "123",
        "address": "somethinghere"
      },
      {
        "id": "456",
        "address": "soemthing"
      }
   ]
} 
SELECT *
FROM   table_name, json_array_elements(json_column) AS data
WHERE  data->>'id' = 123;
省略这一部分:

json_array_elements(t.json_col->'emails')

使用Postgres 9.4+中的JSONB列,您可以使用contains运算符
@>
查询数组中的元素:

SELECT * FROM jsontest WHERE data @> '{ "emails": [{ "id": "123" }] }';
有关更多详细信息,请参阅

以下是一个工作示例:

CREATE TABLE jsontest(data JSONB NOT NULL);
INSERT INTO jsontest VALUES (
  '{
     "name": "foo",
     "id": "123",
     "emails": 
     [
       {
         "address": "somethinghere",
         "id": "123"
       },
       {
         "address": "soemthing",
         "id": "456"
       }
     ]
  }'
);
SELECT * FROM jsontest WHERE data @> '{ "emails": [{ "id": "123" }] }';

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

(1行)

这是我迄今为止看到的关于这类问题的最佳答案。@ErwinBrandstetter很抱歉,但你能帮我解决这个问题吗:(提前谢谢!)我在Postgres 9.4.4上试过了,但没有用:这非常有用,我一直在努力与CTE合作,试图让它发挥作用,这正好很好地解决了我的需要。谢谢如何按id 123删除地址?
从jsontest中删除数据@>'{“电子邮件”:[{“id”:“123”}]}'