我有一個表,它有一個名為的列tags,它是一個 jsonb 型別的列。
Table "public.tagged_products"
Column | Type | Modifiers
------------- ----------------------------- --------------------------------------------------------------
id | integer | not null default nextval('tagged_products_id_seq'::regclass)
item_id | character varying(255) | not null
tags | jsonb | not null default '{}'::jsonb
create_time | timestamp(0) with time zone | not null default now()
update_time | timestamp(0) with time zone | not null default now()
active | boolean | not null default true
Indexes:
"tagged_products_pkey" PRIMARY KEY, btree (id) "uc_attributes_uid" UNIQUE CONSTRAINT, btree (tags, item_id) "lots_idx_attr" gin (tags)
"lots_idx_uid" btree (item_id)
樣本資料
-[ RECORD 1 ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
id | 17
item_id | 9846
tags | {"coo": "IN", "owner": "Online", "vastxt": "", "ecc_ibd": "180000010", "hm_order": "400000010", "entitled_to_dispose": "W141"}
create_time | 2022-02-24 11:49:23 05:30
update_time | 2022-02-24 11:49:23 05:30
active | t
現在我有一組要搜索的值(不是鍵,因為我事先沒有/不知道鍵),如下所示:
["IN", "Online"]并且這兩個都需要出現在記錄標簽的值中。
我提到并嘗試了很多東西但失敗了
參考:如何在postgres中過濾json任意鍵的值
我應該如何為這個用例撰寫查詢?
uj5u.com熱心網友回復:
假設您的搜索詞在一個jsonb陣列中,將其轉換為text[],將tags列中的值轉換為text[],然后使用@>contains 運算子:
with search_terms as (
select array_agg(el) as search_array
from jsonb_array_elements_text('["IN", "Online"]') as et(el)
)
select m.id, m.tags
from search_terms s
cross join mytable m
cross join lateral jsonb_each_text(tags) t(k,v)
group by m.id, m.tags, s.search_array
having array_agg(t.v) @> s.search_array
;
作業小提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/465867.html
標籤:sql 数组 PostgreSQL jsonb postgresql-9.5
上一篇:如何使用選擇子查詢批量插入
