繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM