简体   繁体   English

在postgres中查询嵌套的Json object

[英]Querying nested Json object in postgres

I have a jsonb column in my table and data is in this format:我的表中有一个 jsonb 列,数据采用以下格式:

[
  {
    "id": 1,
    "DATA": {
      "a": "XXX",
      "key": "value1"
    }
  },
  {
    "id": 2,
    "DATA": {
      "a": "XXX",
      "key": "value2"
    }
  }
]

I would like to get the count of rows in which key = value1 .我想获取key = value1的行数。 I tried some queries like:我尝试了一些查询,例如:

select count(t.id) 
from my_table t, 
jsonb_array_elements(summary->'DATA') elem 
where elem->>'key' = 'value1';

It returned 0 rows, though there are rows in db with that key value pair.它返回 0 行,尽管 db 中有具有该键值对的行。 Thanks in advance,提前致谢,

Use jsonb_array_elements() for the column summary as it is in the form of json array.使用jsonb_array_elements()作为列summary ,因为它采用 json 数组的形式。

select count(distinct t.id) 
from my_table t
cross join jsonb_array_elements(summary) elem 
where elem->'DATA'->>'key' = 'value1';

Alternatively, you can get rid of the function using @> operator:或者,您可以使用@>运算符摆脱 function :

select count(t.id) 
from my_table t
where summary @> '[{"DATA":{"key":"value1"}}]'

The second solution should be faster.第二种解决方案应该更快。

Db<>fiddle. Db<>小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM