【发布时间】:2016-01-11 15:18:30
【问题描述】:
无法从 postgres 中的 jsonb 中提取和比较两个数组以进行重叠检查。有这个功能吗?
people_favorite_color 表中的示例:
{
"person_id":1,
"favorite_colors":["red","orange","yellow"]
}
{
"person_id":2,
"favorite_colors":["yellow","green","blue"]
}
{
"person_id":3,
"favorite_colors":["black","white"]
}
数组重叠 postgres 测试:
select
p1.json_data->>'person_id',
p2.json_data->>'person_id',
p1.json_data->'favorite_colors' && p2.json_data->'favorite_colors'
from people_favorite_color p1 join people_favorite_color p2 on (1=1)
where p1.json_data->>'person_id' < p2.json_data->>'person_id'
预期结果:
p1.id;p2.id;likes_same_color
1;2;t
1;3;f
2;3;f
--编辑-- 尝试转换为 text[] 会导致错误:
select
('{
"person_id":3,
"favorite_colors":["black","white"]
}'::jsonb->>'favorite_colors')::text[];
ERROR: malformed array literal: "["black", "white"]"
DETAIL: "[" must introduce explicitly-specified array dimensions.
【问题讨论】:
-
尝试将
p1.json_data->'favorite_colors'的结果转换为text[],那么您应该可以使用通常的数组重叠运算符。 -
请使用 JSONLint 验证 json 值。
-
@a_horse_with_no_name 编辑了问题以修复格式并包含投射结果
标签: arrays postgresql jsonb