【问题标题】:Split array(bigint) to multiple rows of bigint将数组(bigint)拆分为多行 bigint
【发布时间】:2020-12-30 05:28:45
【问题描述】:

我正在查询一些 data (SQL, presto),每个项目都可以是另一个项目的父项或子项。 parent IDschild IDs 作为数组 (bigint) 存储在该主 ID 的行中。每个任务都可以是多个父母的孩子。

它看起来像:

id | parent_ids | child_ids
1 | [3] | []
2 | [3] | []
3 | [] | [2,1]
4 | [] | [5]
5 | [4, 6] | []
6 | [] | [5]

我想要一个所有parent Ids 和每个children 的列表作为该父级的附加行:

id | child
3 | 1
3 | 2
4 | 5
6 | 5

知道如何实现这一目标吗?

【问题讨论】:

    标签: sql arrays presto


    【解决方案1】:

    我想你想要:

    select p.parent_id as id, t.id as child_id
    from t cross join 
         unnest(t.parent_ids) p(parent_id)
    

    【讨论】:

    • 我认为已经完成了!谢谢!我想我理解这是如何工作的:unnest parent_ids 将在列表中为每个 id 提取每个父 id 并创建一个新行,原始行 id 成为子 id,该行的未嵌套父 id 成为 id。我可以看到 p(parent_id) 的目的是(可能)将未嵌套的 parent_ids 列命名为 parent_id,但我不明白为什么 p()?你能解释一下吗?
    • p(parent_id) 只是未嵌套列的名称。
    • 请注意,如果parent_ids 可能为NULL 或为空,并且您仍希望在输出中保留此类行,则可能需要使用LEFT JOIN UNNEST(t.parent_ids) p(parent_id) ON true 而不是CROSS JOIN UNNEST(t.parent_ids) p(parent_id)
    • 谢谢 - 该编辑帮助我理解。在这种情况下,p 是表的名称,因此可以将其读取为“unnest(t.parent_ids) as p(parent)id”吗?感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 2013-06-10
    • 2023-03-11
    • 1970-01-01
    • 2021-05-22
    相关资源
    最近更新 更多