[英]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”的行?
謝謝你的幫助! 干杯!
一個選項使用exists
和jsonb_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.