首页 > 解决方案 > Postgres 获取具有逗号分隔值的列表

问题描述

我正在研究 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。我需要为电话做同样的事情

标签: postgresqlstring-aggregation

解决方案


按员工汇总并使用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;

推荐阅读