mysql重复记录删除,保留一条数据

背景:这是一张品牌表,品牌和城市确定是一条数据。
脚本思路:1.根据品牌名和城市进行分组查询出来重复的品牌名,2.再查询出来重复数据的最小id。3.删除这些品牌名但是不包括2查询出来的id。

sql脚本1:

DELETE 
FROM
    dw_brand_expand 
WHERE
    brand_name IN (SELECT brand_name FROM dw_brand_expand GROUP BY brand_name, city_name HAVING COUNT( * ) > 1) 
    AND id NOT IN (SELECT min( id ) FROM dw_brand_expand GROUP BY brand_name, city_name HAVING count( * ) > 1)
mysql重复记录删除,保留一条数据_第1张图片
执行结果1.png

报错了,报错信息如上图,意思是:不能在FROM子句中指定更新的目标表。解决方案:嵌套一层,取个别名,如下。

sql脚本2:

DELETE 
FROM
    dw_brand_expand 
WHERE id in
(select id from (select id from dw_brand_expand where 
    brand_name IN (SELECT brand_name FROM dw_brand_expand GROUP BY brand_name, city_name HAVING COUNT( * ) > 1) 
    AND id NOT IN (SELECT min( id ) FROM dw_brand_expand GROUP BY brand_name, city_name HAVING count( * ) > 1)) as tmpresult)
mysql重复记录删除,保留一条数据_第2张图片
执行结果2.png

执行成功,0行是因为执行过一次了,起到显示作用即可。

你可能感兴趣的:(mysql重复记录删除,保留一条数据)