查找与JSONB列中的哈希数组中的列表不匹配的所有值

时间:2018-03-28 05:32:51

标签: sql json postgresql jsonb

假设我有一个名为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"]

2 个答案:

答案 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