postgresql - 检查 Postgres json 数组是否与另一个数组相交
问题描述
是否有一个 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
解决方案
您可以使用 (when using ) 或 (when using ) 扩展 JSON 数组,或使用( when jsonb_array_elements
usingjsonb
json_array_elements
json
)或(when using )直接扩展为文本,然后使用 将它们转换为 PostgreSQL 数组。jsonb_array_elements_text
jsonb
json_array_elements_text
json
array_agg
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)
推荐阅读
- javascript - 如何通过类名和特定数据集值查询SelectorAll?
- google-chrome - 如何在空手道 UI 测试中启用 acceptInsecureCerts
- nginx - Nginx 不传递 NodeJS 服务器的响应标头
- ansible - Ansible:通过 hostvars[inventory_hostname].host_name 总结节点任务结果
- redis - 如何在前端获取 socket.on 函数?事件被触发和处理。我正在使用 socket.io、NodeJS 服务器和 Redis.io
- r - 克里格中的“CRS 对象有注释,在输出中丢失”
- python-2.7 - 恢复 python 模块
- flutter - Flutter:导航离开时如何关闭 SnackBar?
- javascript - JavaScript 嵌套数组不能使用值?
- python - 在Python中将二元运算符重载为一元