[英]PostgreSQL: Query elements in a JSON array
I have a database table like the following: 我有一个如下的数据库表:
---------------------------------------
| id | json_array (jsonb) |
---------------------------------------
| 1 | [{"a": 1}, {"a": 5}, {"a": 1}] |
| 2 | [{"a": 2}] |
| 3 | [{"a": 1}] |
---------------------------------------
I want to use PostgreSQL's JSON query abilities to select certain sub dictionaries in the json_array
array, eg dictionaries where "a": 1
. 我想使用PostgreSQL的JSON查询功能来选择
json_array
数组中的某些子字典,例如,其中"a": 1
字典。
The output should be 输出应为
------------------
| id | json_dict |
------------------
| 1 | {"a": 1} |
| 1 | {"a": 1} |
| 3 | {"a": 1} |
------------------
The following query works for the first element in each array, but I want to check for all of them: 以下查询适用于每个数组中的第一个元素,但我想检查所有这些元素:
SELECT id, json_array -> 0
FROM my_table
WHERE json_array -> 0 -> "a" = 1;
Assuming this is a JSONB column, you can use the @>
operator with a json object: 假设这是JSONB列,则可以将
@>
运算符与json对象一起使用:
select *
from my_table
where json_array @> '[{"a": 1}]';
Online example: https://rextester.com/SACUDU51598 在线示例: https : //rextester.com/SACUDU51598
If you want all objects as rows, you need to unnest the array: 如果要将所有对象都作为行,则需要取消嵌套该数组:
select t.id, e.obj
from data t
cross join jsonb_array_elements(json_array) as e(obj)
where e.obj = '{"a": 1}'
Online example: https://rextester.com/DLG27322 在线示例: https : //rextester.com/DLG27322
You can expand your array elements into one element each row with jsonb_array_elements()
. 您可以使用
jsonb_array_elements()
将数组元素扩展为每一行一个元素。 This can be filtered: 可以过滤:
SELECT
id,
elems.value
FROM
mytable,
jsonb_array_elements(data) elems
WHERE
elems.value = '{"a":1}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.