PHP MySQL consolidate column where other column has duplicates

时间:2016-04-21 22:24:59

标签: php mysql unique

I have a MySQL table that has three columns, the first is a unique key (INT(11) AUTO_INCREMENT), the next is an indexed value (VARCHAR(255)) and the third is a description (TEXT). There are duplicate values in the second column, but each row has a different description. I want to remove all rows where the second column is duplicated but append each description of the same indexed value to the first instance the value, and breaking string with a semicolon and space.

For example, my table looks like this:

cid   | word    | description
------------------------------
1     | cat     | an animal with wiskers
2     | cat     | a house pet
3     | dog     | a member of the canine family
4     | cat     | a cool person

I want to change the table to look like this:

cid   | word    | description
------------------------------
1     | cat     | an animal with wiskers; a house pet; a cool person
3     | dog     | a member of the canine family

I'm not adverse to using a PHP script to do this, but would prefer MySQL. The table has over 170,000 rows and would take PHP a long time to loop over it.

2 个答案:

答案 0 :(得分:2)

SQL:

select `cid`,`word`,group_concat(`description` SEPARATOR '; ') as `description` from `test_table` group by `word`;

Ok.. you can copy all the data into another table, and rename it then..

insert into `test_new` (`cid`,`word`,`desc`) (select `cid`,`word`,group_concat(`desc` SEPARATOR '; ') as `description` from `test_table` group by `word`);

mysql> describe `test_new`;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(11)  | YES  |     | NULL    |       |
| word  | char(10) | YES  |     | NULL    |       |
| desc  | text     | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> select * from `test_new`;
+------+------+---------------------+
| id   | word | desc                |
+------+------+---------------------+
|    1 | cat  | desc1; desc2; desc4 |
|    3 | dog  | desc3               |
+------+------+---------------------+
2 rows in set (0.00 sec)

答案 1 :(得分:0)

如前所述,您可以创建一个新表并复制信息,您也可以分两步完成,但只有在修改旧表时没有问题:

UPDATE tableOld AS N1, tableOld AS N2 
SET N1.description = concat(concat(N1.description,"; "),N2.decription))
WHERE N2.word = N1.word

insert into tableNew (cid,name,description)select * from tableOld group by word