我想从我的mysql表中删除所有重复的记录。我试过这个,但我有以下错误:
您无法指定目标表格' maTable'用于FROM子句中的更新。
我已经看到了另一个关于此问题的主题,但我希望您了解我的查询错误以及如何使其工作
DELETE
FROM maTable
WHERE id_table IN (SELECT id_table
FROM maTable GROUP by id_table
HAVING COUNT(id_table)>1)
答案 0 :(得分:2)
这是MySQL的一个限制。一种方法是使用join
:
DELETE m
FROM maTable m JOIN
(SELECT id_table, COUNT(*) as cnt
FROM maTable
GROUP BY maTable
) mm
ON mm.id_table = m.id_table
WHERE cnt > 1;
如果要删除除一个重复项之外的所有重复项(即保留其中一个值),则最好使用某种唯一列,例如创建日期:
DELETE m
FROM maTable m LEFT JOIN
(SELECT id_table, min(creation_date) as mincd
FROM maTable
GROUP BY maTable
) mm
ON mm.id_table = m.id_table AND m.creation_date = mm.mincd
WHERE mm.id_table IS NULL;
答案 1 :(得分:1)
尝试在子查询中包装IN
查询:
DELETE
FROM maTable
WHERE id_table IN (
SELECT id_table
FROM (SELECT id_table
FROM maTable
GROUP by id_table
HAVING COUNT(id_table)>1) AS t)