简体   繁体   English

PostgreSQL 通过 JSON object 查询数组

[英]PostgreSQL query by JSON object in array

Folks,伙计们,

I have a following table in my PostgreSQL.我的 PostgreSQL 中有一个下表。

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

I keep JSON array in my field1 as per example below:我将 JSON 数组保留在我的 field1 中,如下例所示:

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

My question is: How do I query for rows that include a specific "id" in that JSON array?我的问题是:如何在 JSON 数组中查询包含特定“id”的行?

Thanks for your help!谢谢你的帮助! Cheers!干杯!

One option uses exists and jsonb_array_elements() :一个选项使用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'
)

You can use the contains operator:您可以使用包含运算符:

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

This operation is able to make use of an index on field1, while a method that relies on jsonb_array_elements cannot be indexed.此操作能够使用 field1 上的索引,而依赖于 jsonb_array_elements 的方法不能被索引。

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

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