选择数组中的最后一个公共元素

时间:2020-05-14 00:28:36

标签: sql arrays postgresql select unnest

我有一个这样的提交表

CREATE TABLE commit (
    id            serial PRIMARY KEY,
    parent_commit_ids  INTEGER[] NOT NULL
);

给出两个提交ID,我试图找到最新的(最远到数组末尾)常见的parent_commit_id。

2 个答案:

答案 0 :(得分:2)

这是一种使用条件聚合的方法。

select max(x.pid) last_common_id
from commits c
cross join lateral unnest(c.parent_commit_ids) with ordinality x(pid, rn)
where c.id in (1, 2)
group by x.rn
having max(x.pid) filter(where c.id = 1) = max(x.pid) filter(where c.id = 2)
order by rn desc limit 1

这假设您要比较提交1和提交2。此想法是取消嵌套每个数组,按元素索引分组,然后使用having子句来过滤匹配的值。然后,您可以排序并选择最匹配的内容。

Demo on DB Fiddle

样本数据(取自问题的评论)

id | parent_commit_ids
-: | :----------------
 1 | {1,4,6,8}        
 2 | {1,4,5}          

结果:

| last_common_id |
| -------------: |
|              4 |

旁注:commit是一个SQL关键字,因此不是表名的理想选择。我改用commits

答案 1 :(得分:0)

如果下面的方法适用于您,请尝试使用自连接

    Select t1.id, max(t2.id) 
    From table t1 join table t2
    on t1.id < t2.id and
    t1.parent_commit_ids = 
      t2.parent_commit_ids 
      Group by t1.id