是否有一个postgres jsonb运算符来检查一组元素中的任何一个元素是否在另一组元素中?
例如:
if ['a', 'b', 'c'] in ['c', 'd', 'e'] = True because c in 2nd set
if ['f', 'g', 'h'] in ['g', 'h', 'i'] = True because of g and h in 2nd set
答案 0 :(得分:1)
您可以使用jsonb_array_elements
(when using jsonb
) or json_array_elements
(when using json
)扩展JSON数组,或者使用jsonb_array_elements_text
(使用jsonb
时)或json_array_elements_text
(使用json
时)直接扩展为文本,然后使用array_agg
将它们转换为PostgreSQL数组。
WITH json_data(x, y) AS (
VALUES ('["a", "b", "c"]'::jsonb, '["c", "d", "e"]'::jsonb),
('["a", "b", "c"]'::jsonb, '["g", "h", "i"]'::jsonb)
)
, array_data AS (
SELECT x, (SELECT array_agg(e) AS arr FROM jsonb_array_elements_text(x) e) AS xarr,
y, (SELECT array_agg(e) AS arr FROM jsonb_array_elements_text(y) e) AS yarr
FROM json_data
)
SELECT x, y, xarr, yarr, xarr && yarr AS with_intersection FROM array_data
这产生了以下结果:
x | y | xarr | yarr | with_intersection
-----------------+-----------------+---------+---------+-------------------
["a", "b", "c"] | ["c", "d", "e"] | {a,b,c} | {c,d,e} | t
["a", "b", "c"] | ["g", "h", "i"] | {a,b,c} | {g,h,i} | f
(2 rows)