kuzey beytar
kuzey beytar

Reputation: 3226

Rename duplicate rows in MySQL

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.

Upvotes: 0

Views: 1389

Answers (3)

frenzy
frenzy

Reputation: 1650

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.

Upvotes: 0

Moshe L
Moshe L

Reputation: 1905

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 (...)).

Upvotes: 0

Martin.
Martin.

Reputation: 10539

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!

Upvotes: 1

Related Questions