我有一个如下所示的数据库表:
---------------------------------------
| id | json_array (jsonb) |
---------------------------------------
| 1 | [{"a": 1}, {"a": 5}, {"a": 1}] |
| 2 | [{"a": 2}] |
| 3 | [{"a": 1}] |
---------------------------------------
我想使用 PostgreSQL 的 JSON 查询功能来选择 json_array
数组中的某些子字典,例如"a": 1
的字典。
输出应该是
------------------
| id | json_dict |
------------------
| 1 | {"a": 1} |
| 1 | {"a": 1} |
| 3 | {"a": 1} |
------------------
以下查询适用于每个数组中的第一个元素,但我想检查所有元素:
SELECT id, json_array -> 0
FROM my_table
WHERE json_array -> 0 -> "a" = 1;
最佳答案
假设这是一个 JSONB 列,您可以对 json 对象使用 @>
运算符:
select *
from my_table
where json_array @> '[{"a": 1}]';
在线示例:https://rextester.com/SACUDU51598
如果您希望所有对象都作为行,则需要取消嵌套数组:
select t.id, e.obj
from data t
cross join jsonb_array_elements(json_array) as e(obj)
where e.obj = '{"a": 1}'
关于sql - PostgreSQL:查询 JSON 数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57202708/