繁体   English   中英

PostgreSQL 通过 JSON object 查询数组

[英]PostgreSQL query by JSON object in array

伙计们,

我的 PostgreSQL 中有一个下表。

CREATE TABLE public.my_table
(
    id uuid NOT NULL,
    name character varying(50) NOT NULL,
    field1 jsonb NOT NULL
)

我将 JSON 数组保留在我的 field1 中,如下例所示:

[
    {
        "id": "abc"
    },
    {
        "id": "def"
    },
    {
        "id": "ghi"
    }
]

我的问题是:如何在 JSON 数组中查询包含特定“id”的行?

谢谢你的帮助! 干杯!

一个选项使用existsjsonb_array_elements()

select *
from my_table t
where exists (
    select 1 from jsonb_array_elements(t.field1) f(obj) where f.obj ->> 'id' = 'abc'
)

您可以使用包含运算符:

select * from my_table where field1 @> '[{"id":"whatever"}]'

此操作能够使用 field1 上的索引,而依赖于 jsonb_array_elements 的方法不能被索引。

暂无
暂无

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

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