mysql - 如何在 mysql 中拆分/反透视 group_concat?

标签 mysql sql database phpmyadmin group-concat

我目前有一个 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/

相关文章:

sql - 如何在不完全读取 blob 的情况下测试 sqlite 表中的 blob 是否不为空?

mysql - 在 MySQL 中重命名表

iphone - 将图像存储和检索到 iphone 的 sqlite 数据库中

带数组的 PHP 更新语句

mysql - 合并来自 2 个 Rails 应用程序的数据?

php - 从已过期的行中删除图像

mysql - 为什么使用 ActiveRecord 而不是 MySql API

mysql - 在数据可能存在或可能不存在时连接表

mysql - MySQL 语句中的聚合结果

php - 使用 php 更新 Mysql