[英]Find all values that do not match a list in array of hashes in JSONB column
可以說我有一個表,其中包含一個名為fields
的JSONB列。 我的表tbl_1
包含以下值,
ID Fields
-------------------------------------------------------------
1 [{"label": "Request For"}, {"label": "Requestor"}]
2 [{"label": "Request For"}, {"label": "Meeting"}, {"label": "XYZ"}]
3 [{"label": "Request For"}, {"label": "Meeting With"}, {"label": "ABC"}]
現在,我有了一個列表["ABC", "Request For", "ZZZ", "ABC"]
。 我想查找單個查詢中表中不存在上述列表中的哪個元素。 上面列表的預期輸出應為["ZZZ"]
where
子句中not exists
使用,例如:
with my_table(if, fields) as (
values
(1, '[{"label": "Request For"}, {"label": "Requestor"}]'::jsonb),
(2, '[{"label": "Request For"}, {"label": "Meeting"}, {"label": "XYZ"}]'),
(3, '[{"label": "Request For"}, {"label": "Meeting With"}, {"label": "ABC"}]')
)
select item
from jsonb_array_elements('["ABC", "Request For", "ZZZ", "ABC"]') as item
where not exists (
select 1
from my_table
cross join lateral jsonb_array_elements(fields)
where value->'label' = item
)
item
-------
"ZZZ"
(1 row)
@>
運算符的替代解決方案,它給出了一個更簡單的執行計划:
select item
from jsonb_array_elements('["ABC", "Request For", "ZZZ", "ABC"]') as item
where not exists (
select 1
from my_table
where fields @> jsonb_build_array(jsonb_build_object('label', item))
)
您可以測試實際數據中哪個更快。
這也有效
SELECT
a.col
FROM
tbl_1 t
CROSS JOIN LATERAL
jsonb_to_recordset(t.fields) as j("label" text)
right join
(
select unnest(ARRAY['ABC', 'Request For', 'ZZZ', 'ABC'])as col
) a
on j."label" = a.col
where j."label" is null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.