简体   繁体   English

PHP MySQL将多列转换为多行

[英]PHP MySQL Convert Multiple Columns into Multiple Rows

So I have a database table that is structured something like this... 所以我有一个结构像这样的数据库表...

NAME | PHONE | EMAIL1 | EMAIL2 | EMAIL3

Those would be my columns, imagine this is a row in that database.. 这些将是我的专栏,想象这是该数据库中的一行。

John | 555-555-5555 | email1@website.com | email2@website.com | email3@website.com

I need to be able to dump these entries to a CSV which I have the code for working already BUT the format is the issue. 我需要能够将这些条目转储到CSV文件中,而我已经有了可以正常工作的代码,但是格式是问题所在。

I need each email to be displayed on a single row with the corresponding name and number, in the following format... 我需要每封电子邮件以以下格式显示在具有相应名称和编号的一行中...

John | 555-555-5555 | email1@website.com
John | 555-555-5555 | email2@website.com
John | 555-555-5555 | email3@website.com

I need to retrieve thousands of rows and display them this way, is there some way using a PHP while loop I can display the rows from my database table in this format? 我需要检索数千行并以这种方式显示它们,是否有某种使用PHP while循环的方式可以以这种格式显示数据库表中的行? Any help is greatly appreciated. 任何帮助是极大的赞赏。

This process is called unpivoting. 此过程称为不可透视。
And is most commonly done with UNION ALL within MySQL. 最常见的是在MySQL中使用UNION ALL完成。

SELECT 
   NAME
 , PHONE
 , EMAIL1 
FROM 
 table

UNION ALL 

SELECT 
   NAME
 , PHONE
 , EMAIL2 
FROM 
 table

UNION ALL 

SELECT 
   NAME
 , PHONE
 , EMAIL3 
FROM 
 table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM