[英]Finding mySQL duplicates, then merging data
我有一個mydb數據庫,有兩百萬行。 數據庫是非交互式的,因此效率不是關鍵。
我所擁有的(簡化)結構是:
`id` int(11) NOT NULL auto_increment
`category` varchar(64) NOT NULL
`productListing` varchar(256) NOT NULL
現在我想解決的問題是,我想在productListing字段上找到重復項,將類別字段上的數據合並為一個結果 - 刪除重復項。
所以給出以下數據:
+----+-----------+---------------------------+
| id | category | productListing |
+----+-----------+---------------------------+
| 1 | Category1 | productGroup1 |
| 2 | Category2 | productGroup1 |
| 3 | Category3 | anotherGroup9 |
+----+-----------+---------------------------+
我最終想要的是:
+----+----------------------+---------------------------+
| id | category | productListing |
+----+----------------------+---------------------------+
| 1 | Category1,Category2 | productGroup1 |
| 3 | Category3 | anotherGroup9 |
+----+----------------------+---------------------------+
在純mySQL查詢或php中,最有效的方法是什么?
我想你正在尋找GROUP_CONCAT
:
SELECT GROUP_CONCAT(category), productListing
FROM YourTable
GROUP BY productListing
我會創建一個新表,插入更新的值,刪除舊表並將新表重命名為舊表的名稱:
CREATE TABLE new_YourTable SELECT GROUP_CONCAT(...;
DROP TABLE YourTable;
RENAME TABLE new_YourTable TO YourTable;
-- don't forget to add triggers, indexes, foreign keys, etc. to new table
SELECT MIN(id), GROUP_CONCAT(category SEPARATOR ',' ORDER BY id), productListing
FROM mytable
GROUP BY
productListing
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.