postgresql - 包含重叠值的数组的有效合并

标签 postgresql postgresql-9.6

给定一个包含整数数组的表,应该合并这些数组,以便所有具有重叠条目的数组最终成为一个数组。

给定表数组

     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

这留下了两个问题:

  1. 它不是递归的(它最多合并 2 个数组)。
    这可能可以通过递归 CTE 来解决。
  2. 合并的数组在输出中再次出现。

非常欢迎任何意见。

最佳答案

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/

相关文章:

sql - 如何创建 POSTGRESQL 中某个键唯一的自动递增修订号?

postgresql - 导入带有外键的 csv

postgresql - PostGIS 升级 2.2.1 -> 2.5.0 数据库导入错误

java - 如何将 Java 模式转换为 Postgres 正则表达式

postgresql - Postgres 准备事务与准备语句

sql - 通过 : more target columns than expressions error 插入一个选择组

javascript - 如何批量创建百万级数据?

postgresql-9.6 - 向 PostgreSQL 中的表添加默认约束

PostgreSQL : ERROR: relation "sequence" does not exist while restoring from dump file

postgresql - PostgreSQL 时间戳转换中的奇怪时区