簡體   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