重命名sql中的重复数据

时间:2011-09-14 12:46:06

标签: mysql sql

我可以使用此查询找出重复数据

   SELECT names FROM group GROUP BY names HAVING count(*) > 1

我能够获取重复数据。我只需要知道如何将这个重复数据重命名为 new

  INPUT
+-----------------+               
| names           |
+-----------------+
| text1           |
| text2           |
| text3           |
| text1           |
| text3           |
| text4           |
+-----------------+

OUTPUT  
+-----------------+
| names           |
+-----------------+ 
| text1           |
| text2           |
| text3           |
| text1 new value |->RENAMED
| text3 new value |->RENAMED
| text4           |
+-----------------+

3 个答案:

答案 0 :(得分:13)

假设您在桌面上有某种主键,例如自动增量ID,您可以执行以下操作。

UPDATE group 
SET names = CONCAT(names,' Copy 1')
WHERE ID IN
(
SELECT MAX(ID) 
FROM group 
GROUP BY names 
HAVING count(*) > 1
);

为了解释,它会找到任何有重复的内容,为该集合中的任何内容选取最大ID,并在其末尾添加“copy 1”。如果你有3次或更多次某些名字,你可能仍然有一些重复。再次运行它,这次使用'copy 2'而不是'copy 1'。继续重复这个过程,直到你摆脱所有的副本。

更新。要从@Yahia借用一个想法并使用UUID,如果你想在一个查询中完成所有操作,你可以执行以下操作。

UPDATE group 
SET names = CONCAT(names, CONCAT ( ' Copy ', UUID_SHORT() ) )
WHERE 
ID NOT IN
(
SELECT MIN(ID) 
FROM group 
GROUP BY names 
HAVING count(*) > 1
) AND
ID IN
(
SELECT ID
FROM group AS G1
INNER JOIN group AS G2
ON G1.names = G2.names AND G1.ID <> G2.ID
);

答案 1 :(得分:2)

使用(根据评论更正)

UPDATE Group 
SET Names = CONCAT(Names, CONCAT ( ' Copy ', UUID_SHORT() ) )
WHERE 
ID NOT IN
(
SELECT MIN(ID) 
FROM group 
GROUP BY names 
HAVING count(*) > 1
) AND
ID IN
(
SELECT ID
FROM group 
GROUP BY names 
HAVING count(*) > 1
);

通过连接一个唯一的UUID_SHORT ...除了具有最小ID的那个之外的所有UUID_SHORT,这使得所有重复项都是唯一的...它保持不变...

答案 2 :(得分:1)

试试这个 -

UPDATE table1 n 
  JOIN (SELECT names FROM table1 GROUP BY names HAVING count(*) > 1) d
    ON n.names = d.names
SET n.names = 'new value';

修改

完整代码 -

CREATE TABLE table1(
  id INT(11) PRIMARY KEY AUTO_INCREMENT,
  names VARCHAR(255) DEFAULT NULL
);    

INSERT INTO table1 VALUES 
  ('text1'),
  ('text2'),
  ('text3'),
  ('text1'),
  ('text3'),
  ('text4');

UPDATE table1 n 
  JOIN (SELECT names, MIN(id) min_id FROM table1 GROUP BY names HAVING COUNT(*) > 1) d
    ON n.names = d.names AND n.id <> d.min_id
SET n.names = CONCAT(n.names, ' new value');

SELECT * FROM table1;

+----+-----------------+
| id | names           |
+----+-----------------+
|  1 | text1           |
|  2 | text2           |
|  3 | text3           |
|  4 | text1 new value |
|  5 | text3 new value |
|  6 | text4           |
+----+-----------------+