[英]How to split / unpivot group_concat in mysql?
我目前在一個視圖中有一列名為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)我希望能夠修改我的視圖以包含每位用戶可變數量的電子郵件。
您可以使用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;
如果願意,可以將這些值插入另一個表中。
不要使用該視圖,因為GROUP_CONCAT()
已經破壞了規范化。 您想使用MySQL的有限SQL功能來模擬數據透視表。
假設您的視圖基於如下所示的“ Contacts
表:
CREATE TABLE Contacts
( id INTEGER NOT NULL
, alt_email_contact VARCHAR(256) NOT NULL
);
而是創建此幫助程序視圖(基本上是RANK() OVER (PARTITION BY id ORDER BY alt_email_contact)
,除了MySQL不支持RANK()
):
CREATE VIEW NumberedContacts AS
SELECT c1.id, c1.alt_email_contact, COUNT(*) AS rank
FROM Contacts c1
INNER JOIN Contacts c2
ON c2.id = c1.id AND
c1.alt_email_contact >= c2.alt_email_contact
GROUP BY c1.id, c1.alt_email_contact;
然后,您可以編寫此查詢或視圖,該查詢或視圖最多提供5個備用電子郵件地址,按字母順序排列:
CREATE VIEW ContactsForImport AS
SELECT c1.id
, c1.alt_email_contact AS email_1
, c2.alt_email_contact AS email_2
, c3.alt_email_contact AS email_3
, c4.alt_email_contact AS email_4
, c5.alt_email_contact AS email_5
FROM NumberedContacts AS c1
LEFT OUTER JOIN NumberedContacts AS c2
ON c1.id = c2.id AND c2.rank = 2
LEFT OUTER JOIN NumberedContacts AS c3
ON c1.id = c3.id AND c3.rank = 3
LEFT OUTER JOIN NumberedContacts AS c4
ON c1.id = c4.id AND c4.rank = 4
LEFT OUTER JOIN NumberedContacts AS c5
ON c1.id = c5.id AND c5.rank = 5
WHERE c1.rank = 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.