【问题标题】:Select last common element in arrays选择数组中的最后一个公共元素
【发布时间】:2020-08-30 09:17:21
【问题描述】:

我有一个这样的提交表

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

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

【问题讨论】:

  • 常见于什么?一些数据和期望的结果会有所帮助。
  • 彼此共有。如果提交 A 包含 parent_commit_ids=[1,4,5] 并且提交 B 包含 parent_commit_ids=[1,4,6,8],则最新的常见 parent_commit_id 将为 4。
  • 所有先前的数组元素也必须匹配?还是只是最后一个? [2,3][1,3] 是否匹配 3[1,2,3,4,5][6, 4] 匹配 4? Postgres 版本?

标签: sql arrays postgresql select unnest


【解决方案1】:

如果它对您有用,请尝试以下使用自加入的方法

    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 

【讨论】:

    【解决方案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

    样本数据(取自问题的 cmets):

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

    结果:

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

    旁注:commit 是 SQL 关键字,因此不是表名的好选择;我改用commits

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 2012-02-21
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多