Rename duplicate rows in MySQL

社会主义新天地 提交于 2019-12-20 06:36:36

问题


There are some similar topics in stackoverflow, but still I didn't succeed to rename my duplicate rows:

CREATE TABLE IF NOT EXISTS `products` (
`product_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`product_code` varchar(32) NOT NULL,
PRIMARY KEY (`product_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

INSERT INTO `products` (`product_id`, `product_code`) VALUES
(1, 'A'),
(2, 'B'),
(3, 'A');

Here first and third rows have same items. I just want to add a suffix like "Copy". And the result would be:

product_id    product_code
-----------  --------------
    1               A
    2               B
    3            A Copy

So how can I solve this problem in MySQL?

Edit: Data above is an example. My original table has more than 3000 products.


回答1:


If you can use PHP, I would recommend you to do it via PHP. I haven't found a way to do this with MySQL. This one will update ALL rows having count > 1, including the original.

UPDATE table
SET product_code = CONCAT(product_code, ' Copy')
GROUP BY product_code
HAVING COUNT(*) > 1

which you don't want. So, if you use php, you can do this (assuming you have low number of rows in your table (3000 is fine))

<?php
$result = mysql_query("SELECT * FROM table");
$rowsCnt = array();
while($row = mysql_fetch_assoc($result)){
    $rows[] = $row;
    $rowsCnt[ $row['product_code'] ]++;
}

foreach($rows as $index => $row) {
    if ($rowsCnt[ $row['product_code'] ] > 1) {
        mysql_query("UPDATE table SET product_code = '".mysql_real_escape_string($row['product_code'])." Copy' LIMIT ".($rowsCnt[ $row['product_code'] ] - 1)
    }
}

Disclaimer: Not tested! Make a backup first!




回答2:


MySQL can do it.

First/ simple Query:

SELECT id, field, count(*) c from ... group by  field having c >1

Second Query, modifed for get IDs to delete:

SELECT  instr(s,mid(s,',')+1) from (
SELECT group_concat(id) s, count(*) c from ... group by  field having c >1)z

looks ugly, but fast (Mid function performance is faster than not in (...)).




回答3:


SELECT  mid(s,instr(s,',')+1) as dubid from (
SELECT group_concat(id ORDER BY id ASC) s, count(*) c from `...` group by  field having c >1) as z

Actually. And better.



来源:https://stackoverflow.com/questions/8213054/rename-duplicate-rows-in-mysql

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