mysql - 将多个电话号码加入列: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 个。
解决方案
我建议您将所有电话放在一个列中:
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;
推荐阅读
- javascript - 如何使 log.csv 文件在一行中记录 400 个 .jpeg 名称(Photoshop/JavaScript)
- c# - csharpcodeprovider:不能使用 Process.Start()
- javascript - Android 上的 Vue.js keyup 事件和 v-model 长度无法按预期工作
- scala - 错误单元不带参数scala
- https - 现有 https 证书添加通配符
- payment - “状态通道”与“小额支付通道”:它们是一样的吗?
- java - 电话编程逻辑
- javascript - 使用 private 时 Typescript 类无法访问
- javascript - 在 D3 图中为 svg 图像添加边框
- python - 在 Python Plotly 中按类别组绘制