给定一个包含整数数组的表,应该合并这些数组,以便所有具有重叠条目的数组最终成为一个数组。
给定表数组
a
------------
{1,2,3}
{1,4,7}
{4,7,9}
{15,17,18}
{18,16,15}
{20}
结果应该是这样的
{1,2,3,4,7,9}
{15,17,18,16}
{20}
正如您所看到的,合并数组中的重复值可能会被删除,并且数组中结果条目的顺序并不重要。这些数组是整数数组,因此可以使用 intarray
模块中的函数。
这将在一个相当大的表上完成,因此性能至关重要。
我的第一个天真的方法是在 &&
运算符上自连接表。像这样:
SELECT DISTINCT uniq(sort(t1.a || t2.a))
FROM arrays t1
JOIN arrays t2 ON t1.a && t2.a
这留下了两个问题:
- 它不是递归的(它最多合并 2 个数组)。
这可能可以通过递归 CTE 来解决。 - 合并的数组在输出中再次出现。
非常欢迎任何意见。
最佳答案
do $$
declare
arr int[];
arr_id int := 0;
tmp_id int;
begin
create temporary table tmp (v int primary key, id int not null);
for arr in select a from t loop
select id into tmp_id from tmp where v = any(arr) limit 1;
if tmp_id is NULL then
tmp_id = arr_id;
arr_id = arr_id+1;
end if;
insert into tmp
select unnest(arr), tmp_id
on conflict do nothing;
end loop;
end
$$;
select array_agg(v) from tmp group by id;
关于postgresql - 包含重叠值的数组的有效合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45640686/