Deleting duplicate rows with sql

后端 未结 5 810
滥情空心
滥情空心 2021-01-17 03:59

I am trying to delete duplicate rows from my mysql table. I\'ve tried multiple queries but I am keep on getting this error: #1093 - You can\'t specify target table \'usa_cit

5条回答
  •  余生分开走
    2021-01-17 04:43

    Try to select the duplicates first, the delete them

    DELETE FROM usa_city WHERE city_id IN
    (
    SELECT city_id FROM usa_city
    GROUP BY city_name, id_state
    HAVING count(city_id) > 1
    )
    

    Hope it helps!!!

    MODIFIED: Based on the comment, if you want to keep one record, you can make a join and keep the lowest value

    DELETE c1 FROM usa_city c1, usa_city c2 WHERE c1.id < c2.id AND 
    (c1.city_name= c2.city_name AND c1.id_state = c2.id_state)
    

    Be sure to make a backup before executing the query above...

提交回复
热议问题