PHP MySQL consolidate column where other column has duplicates

≯℡__Kan透↙ 提交于 2020-01-07 02:39:23

问题


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.


回答1:


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)



回答2:


As was mentioned before, you can create a new table and copy the info, you can also do it in two steps, but only if there´s no problem with modifying the old table:

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


来源:https://stackoverflow.com/questions/36781495/php-mysql-consolidate-column-where-other-column-has-duplicates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!