首页 > 解决方案 > 将多个电话号码加入列:phone1、phone2、phone3

问题描述

我想将多个电话号码加入客户以进行完整的 CSV 导出,而不会出现重复条目​​。我拥有的数据结构:

顾客

ID
1 约翰 能源部
2 最大限度 佩恩

电话

ID 客户ID 数字
1 1 12345679
2 1 987654321
3 1 456789451
4 2 +67987654321

期望的选择结果:

ID 电话1 电话2 电话3 电话4
1 约翰 能源部 12345679 987654321 456789451

电话号码数量限制为 9 个。

标签: mysqlsqldatabase

解决方案


我建议您将所有电话放在一个列中:

select c.*, group_concat(p.number order by p.id) as numbers
from customer c left join
     phones p
     on c.id = p.customer_id
group by c.id;

(注意:这里假设customer(id)是 的主键customer。)

如果你想要单独的列,你可以使用条件聚合来代替:

select c.*, 
       max(case when seqnum = 1 then p.number end) as phone_1,
       max(case when seqnum = 2 then p.number end) as phone_2,
       . . .
from customer c left join
     (select p.*,
             row_number() over (partition by customer_id order by p.id) as seqnum
      from phones p
     ) p
     on c.id = p.customer_id
group by c.id;

推荐阅读