簡體   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