开发背景:
最近在做一个批量数据导入到MySQL数据库的功能,从批量导入就可以知道,这样的数据在插入数据库之前是不会进行重复判断的,因此只有在全部数据导入进去以后在执行一条语句进行删除,保证数据唯一性。
下面话不多说了,来一起看看详细的介绍吧
实战:
表结构如下图所示:
表明:brand
操作:
使用SQL语句查询重复的数据有哪些:
1
2
3
|
SELECT * from brand WHERE brandName IN(
select brandName from brand GROUP BY brandName HAVING COUNT(brandName)>1 #条件是数量大于1的重复数据
)
|
使用SQL删除多余的重复数据,并保留Id最小的一条唯一数据:
注意点:
错误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”
原因是:不能将直接查处来的数据当做删除数据的条件,我们应该先把查出来的数据新建一个临时表,然后再把临时表作为条件进行删除功能
1
2
3
4
5
|
正确SQL写法:
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)
#查询显示重复的数据都是显示最前面的几条,因此不需要查询是否最小值
|
结果如下图:
(责任编辑:IT) |