我目前有一个 View ,其中有一个名为 alt_email_contact 的列,我使用 group_concat 函数来获取与一个联系人关联的多封电子邮件。但是我希望能够提取每封电子邮件并为每封电子邮件创建一个单独的列。
示例:
id email
1 SkyW@gmail.com, SW@gmail.com, WW@gmail.com, WalterW@gmail.com
电子邮件的数量会因一个用户而异,因此每个用户不会总是有四封电子邮件。我想像这样为每封电子邮件创建一个新列:
id email_1 email_2 email_3 email_4
1 SkyW@gmail.com SW@gmail.com WW@gmail.com WalterW@gmail.com
(我正在使用 phpmyadmin)我希望能够修改我的 View 以包含每个用户的可变数量的电子邮件。
最佳答案
您可以使用substring_index()
来实现您想要的。它不是很漂亮,但它会起作用:
select id,
substring_index(emails, ', ', 1) as email_1
(case when length(emails) - length(replace(emails, ',', '')) >= 1
then substring_index(substring_index(emails, ', ', 2), ', ', -1)
end) as email_2,
(case when length(emails) - length(replace(emails, ',', '')) >= 2
then substring_index(substring_index(emails, ', ', 3), ', ', -1)
end) as email_3,
(case when length(emails) - length(replace(emails, ',', '')) >= 3
then substring_index(substring_index(emails, ', ', 4), ', ', -1)
end) as email_4,
(case when length(emails) - length(replace(emails, ',', '')) >= 4
then substring_index(substring_index(emails, ', ', 5), ', ', -1)
end) as email_5
from table t;
如果愿意,您可以将这些值插入到另一个表中。
关于mysql - 如何在 mysql 中拆分/反透视 group_concat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29500186/