假设我有一个名为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"]
答案 0 :(得分:1)
在not exists
子句中使用where
,例如:
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))
)
您可以测试实际数据哪一个更快。
答案 1 :(得分:1)
这也有效
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