最近在做一个批量数据导入到MySQL数据库的功能,从批量导入就可以知道,这样的数据在插入数据库之前是不会进行重复判断的,因此只有在全部数据导入进去以后在执行一条语句进行删除,保证数据唯一性。
表明:brand
SELECT * from brand WHERE brandName IN(
select brandName from brand GROUP BY brandName HAVING COUNT(brandName)>1 #条件是数量大于1的重复数据
)
错误SQL:DELETE FROM brand WHERE brandName IN (select brandName from brand GROUP BY brandName HAVING COUNT(brandName)>1)
AND Id NOT IN (select MIN(Id) from brand GROUP BY brandName HAVING COUNT(brandName)>1)
提示: You can't specify target table 'brand' for update in FROM clause 不能为FROM子句中的更新指定目标表“brand”
原因是:不能将直接查处来的数据当做删除数据的条件,我们应该先把查出来的数据新建一个临时表,然后再把临时表作为条件进行删除功能
DELETE FROM brand WHERE brandName IN (SELECT brandName FROM (SELECT brandName FROM brand GROUP BY brandName HAVING COUNT(brandName)>1) e)
AND Id NOT IN (SELECT Id FROM (SELECT MIN(Id) AS Id FROM brand GROUP BY brandName HAVING COUNT(brandName)>1) t)
#查询显示重复的数据都是显示最前面的几条,因此不需要查询是否最小值
这是老飞飞的前辈给了一个更加方便,简洁的写法(非常感谢大佬的方法):
DELETE FROM brand WHERE Id NOT IN (SELECT Id FROM (SELECT MIN(Id) AS Id FROM brand GROUP BY brandName) t)
这句的意思其实就是,通过分组统计出数据库中不重复的最小数据id编号,让后通过 not in 去删除其他重复多余的数据。
很多东西都是需要自己一步一步的去探究的,当然网上的建议也是非常宝贵的借鉴和资源,无论做什么开发我们都需要理解它的工作原理才能够更好的掌握它。