select * FROM `test` WHERE `name` in ( select a.`name` from( SELECT `name` FROM `test` GROUP BY `name` HAVING COUNT(*) >1 )a ) and `id` not in ( select b.`id` from( select min(`id`) as id from test group by `name` having count(*)>1 )b )
主要思路是IN和NOT IN,用IN来查出哪些是重复的,然后用NOT IN来保留一条;
每个子查询中通过HAVING函数来判断重复;
mysql中不能在更新或删除表的同时去查询这个表,因此需要增加一个字表,否则会报错:
You can‘t specify target table ‘test‘ for update in FROM clause