PHP Mysql合并值(删除重复的电子邮件但保留值)

时间:2017-08-27 14:16:48

标签: php mysql

我在mysql中有一个包含电子邮件的表。大多数电子邮件都是重复的,但每个重复的电子邮件都包含col_1col_2col_3col_4中的不同值。我想合并它们(删除重复项)并保留值。最终结果应该像第二张表一样。

+-----------------------------------------------------+-------++-------++-------++-------+
| email                                               | col_1 || col_2 || col_3 || col_4 |
+-----------------------------------------------------+-------++-------++-------++-------+
| a@a.com                                             |     1 ||     0 ||     0 ||     0 |
| b@b.com                                             |     0 ||     0 ||     1 ||     0 |
| a@a.com                                             |     0 ||     1 ||     0 ||     0 |
| d@d.com                                             |     1 ||     0 ||     0 ||     0 |
| a@a.com                                             |     0 ||     0 ||     0 ||     1 |
| b@b.com                                             |     0 ||     1 ||     0 ||     0 |
| d@d.com                                             |     0 ||     0 ||     0 ||     1 |
+-----------------------------------------------------+-------++-------++-------++-------+

我需要合并电子邮件列,但要保留col_1col_2col_3col_4

+-----------------------------------------------------+-------++-------++-------++-------+
| email                                               | col_1 || col_2 || col_3 || col_4 |
+-----------------------------------------------------+-------++-------++-------++-------+
| a@a.com                                             |     1 ||     1 ||     0 ||     1 |
| b@b.com                                             |     0 ||     1 ||     1 ||     0 |
| d@d.com                                             |     1 ||     0 ||     0 ||     1 |
+-----------------------------------------------------+-------++-------++-------++-------+

1 个答案:

答案 0 :(得分:4)

我认为最简洁的方法是创建另一个表并在其中插入您真正想要的值。然后,删除原始表并重命名新表:

CREATE TABLE yourTableNew (email varchar(255), col_1 int, col_2 int, col_3 int, col_4 int)
INSERT INTO yourTableNew (email, col_1, col_2, col_3, col_4)
SELECT
    email,
    SUM(col_1),
    SUM(col_2),
    SUM(col_3),
    SUM(col_4)
FROM yourTable
GROUP BY email;

DROP TABLE IF EXISTS yourTable;
RENAME TABLE yourTableNew TO yourTable;