MySql删除重复数据只保留最小id的那条数据。某某公司的临时面试题

错误代码:

DELETE 
FROM
	payment 
WHERE
	serial IN ( SELECT serial FROM payment GROUP BY serial HAVING count(*) > 1 ) 
	AND id NOT IN ( SELECT min( id ) AS id FROM payment GROUP BY serial HAVING count( serial ) > 1 );

错误提示:

MySql删除重复数据只保留最小id的那条数据。某某公司的临时面试题_第1张图片 

正确代码: 使用临时表

DELETE 
FROM
	payment 
WHERE
	serial IN ( select serial from  (SELECT serial FROM payment GROUP BY serial HAVING count(*) > 1) a ) 
	AND id NOT IN ( select id from (SELECT min( id ) as id  FROM payment GROUP BY serial HAVING count( serial ) > 1)b  );
	

效果:

实验前数据

执行sql: 

 MySql删除重复数据只保留最小id的那条数据。某某公司的临时面试题_第2张图片

你可能感兴趣的:(mysql)