我有一张数据表sw_goods,里面存储了goods_id,goods_name字段,其中goods_id字段为自增主键,goods_name字段里面有 重复的记录。
我希望删除goods_name字段的重复记录。
思路1:
在原表上直接操作:通过主键删除重复记录
1.先查询id最小的重复记录
SELECT MIN(goods_id )FROM sw_goods GROUP BY goods_name ;
2.删除
DELETE goods_id FROM sw_goods WHERE goods_id NOT IN (SELECT MIN(goods_id) FROM sw_goods GROUP BY goods_name) ;
可是报错了:
ERROR 1093 (HY000): You can’t specify target table ‘student’ for update in FROM clause
原因是:更新数据时使用了查询,而查询的数据又做了更新的条件,mysql不支持这种方式。
如何规避这种问题?
再加一层封装:
DELETE FROM sw_goods WHERE goods_id NOT IN (SELECT minid FROM (SELECT MIN(goods_id )FROM sw_goods GROUP BY goods_name ) AS b);
执行成功。
思路2:
按goods_name分组,把最小的id保存到临时表,删除id不在最小id集合的记录,如下:
1.创建临时表
CREATE TEMPORARY TABLE tmp_name AS SELECT MIN(goods_id) AS minid FROM sw_goods GROUP BY goods_name;
2.执行删除
DELETE FROM sw_goods WHERE goods_id NOT IN (SELECT minid FROM temp_name);