删除重复行并合并单元格值mysql

时间:2013-06-13 07:36:02

标签: mysql

我有一个MySQL表,它有三列:

Name           | Email               | BDate
---------------------------------------------------------
John Doe       | jdoe@company.com    | June 1, 1980
Kelly Smith    |                     | June 2, 1983
Richmond White | rwhite@company.com  | 
John Doe       |                     | 
Kelly Smith    | ksmith@company.com  | 
Richmond White |                     | June 3, 1984

我想要做的是删除重复的名称并合并单元格值。我希望我的桌子看起来像这样:

Name           | Email               | BDate
---------------------------------------------------------
John Doe       | jdoe@company.com    | June 1, 1980
Kelly Smith    | ksmith@company.com  | June 2, 1983
Richmond White | rwhite@company.com  | June 3, 1984

我的查询如何返回我的欲望表?

提前致谢!

2 个答案:

答案 0 :(得分:2)

查询:

<强> SQLFIDDLEExample

SELECT t1.Name, 
       MAX(t1.Email) Email, 
       MAX(t1.BDate) BDate
FROM Table1 t1
GROUP BY t1.Name

结果:

|           NAME |              EMAIL |        BDATE |
------------------------------------------------------
|       John Doe |   jdoe@company.com | June 1, 1980 |
|    Kelly Smith | ksmith@company.com | June 2, 1983 |
| Richmond White | rwhite@company.com | June 3, 1984 |

答案 1 :(得分:0)

一个选项是使用以下查询创建新表,然后删除旧表:

SELECT Name, GROUP_CONCAT(Email) AS Email, GROUP_CONCAT(BDate) AS DBate
FROM YourTable
GROUP BY Name