【问题标题】:Postgres to fetch the list having comma separated valuesPostgres 获取具有逗号分隔值的列表
【发布时间】:2020-09-03 00:41:41
【问题描述】:

我正在使用 Postgres SQL 并有以下联接查询,当我执行此查询时,我会为每个员工获得两到 3 条记录,因为每个员工都有 3 种不同类型的电子邮件地址 1)家庭地址 2)办公室地址 3)社交地址。

select * from root.employee c
full outer join root.employee_email ce
on c.employee_id = ce.employee_id
order by c.employee_id limit 1000 offset 0;

我想要的是 employee_email.email 列在输出中给出逗号分隔值,我们该怎么做?

注意:我在 DB 中有近 100 万条记录,将使用 Spring Batch 将数据从 Postgres 迁移到 MongoDB。我需要为电话做同样的事情

【问题讨论】:

    标签: postgresql string-aggregation


    【解决方案1】:

    按员工汇总并使用string_agg

    select
        c.employee_id,         -- or just c.* assuming employee_id is a PK
        string_agg(ce.email, ',') as emails
    from root.employee c
    full outer join root.employee_email ce
        on c.employee_id = ce.employee_id
    group by
        c.employee_id
    order by
        c.employee_id
    limit 1000
    offset 0;
    

    【讨论】:

    • 我需要做什么才能从两个表中获取所有字段?
    • employee.employee_id是主键列吗?
    • 对,但我需要从结果集中映射所有字段并在 Spring Batch 中创建对象
    • 是的,employee.employee_id 是主键列及其 UUID
    • @JeffCook 然后您应该能够选择employee 表中的所有列,q.v。更新的答案。至于另一个表,我们必须以某种方式聚合它的列。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多