将mysql表合并为两个字段

时间:2017-01-02 09:43:17

标签: php mysql

我有这张桌子:

first_name  |   last_name   |   mobile  |   email
-------------------------------------------------------
a           |   b           |   123     |
c           |   d           |   456     |
a           |   b           |           | ab@gmail.com
c           |   d           |           | cd@gmail.com

我希望将这些表组合起来并获得如下报告:

first_name  |   last_name   |   mobile  |   email
-------------------------------------------------------
a           |   b           |   123     | ab@gmail.com
c           |   d           |   456     | cd@gmail.com

我试图像这样分组:

SELECT * FROM table GROUP BY first_name AND last_name

2 个答案:

答案 0 :(得分:3)

分组逗号时将列分开。还可以使用max()获取未分组列的值,以避免获取空字符串

SELECT first_name, last_name, 
       max(mobile) as mobile, max(email) as email
FROM your_table 
GROUP BY first_name, last_name

答案 1 :(得分:0)

试试这个:

 Select t1.first_name ,t1.last_name,t1.mobile,t2.email from (select * from table where mobile != '') as t1 inner join (select * from table where email != '') as t2 on t1.first_name = t2.first_name;