Wednesday, October 8, 2014

MySQL, check duplication and delete all duplication and keep one.




For example, we have names MySQl table:
SELECT * FROM names;
+----+--------+
| id | name   |
+----+--------+
| 1  | nissan |
| 2  | nissan |
| 3  |  GM    |
| 4  |  EM    |
| 5  |  GM    |
| 6  |  EM    |
+----+--------+
First we want to check duplication:
SELECT distinct name, count(name) FROM `names` group by name having count(name)>1;

Delete duplication and keep the row with the lowest id value:

DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name

 

No comments:

Post a Comment