我有一个包含记录的表,我想删除所有重复的记录
DELETE FROM 'table'
WHERE 'field' IN
(
SELECT 'field' FROM 'table' GROUP BY 'field'
HAVING (COUNT('field')>1)
)
为什么这不起作用?
答案 0 :(得分:6)
也许您可以使用命令DISTINCT
进行探索,以便仅选择基于字段的唯一记录。
您可以使用基于唯一条目创建新表。 举个例子......
CREATE TABLE nonDuplicates
SELECT DISTINCT * FROM yourTable group by field
答案 1 :(得分:1)
这会给你带来不止一个结果: -
SELECT field FROM `table`
GROUP BY field
HAVING (COUNT('field)>1
尝试通过以下方式更改此内容:
SELECT TOP 1 field
FROM `table`
GROUP BY field
HAVING (COUNT(field)>1
答案 2 :(得分:0)
首先获取所有重复项并将它们存储在数组中。
SELECT field
FROM `table`
GROUP BY field
HAVING COUNT('field') > 1
现在让你的php保存一个你想要的结果,然后执行
DELETE
FROM `table`
WHERE field IN (your values) AND field != savedID
答案 3 :(得分:0)
MySQL有一个非常令人讨厌的限制,它不能使用在子选择中更新/删除/插入的表。
但您可以通过加入要删除的表(而不是使用子选择)来解决此问题。
假设您的表中有某种唯一标识符(我在以下语句中假设列id
):
DELETE d
FROM table_with_duplicates d
JOIN (
SELECT min(id) as min_id, field
FROM table_with_duplicates
GROUP BY field
) keep ON keep.field = d.field
AND keep.min_id <> d.id;
这将为每个重复项保留一行(id
列中具有lowes值的那一行)。
如果您要删除所有重复行(不至少保留一行),只需删除AND keep.min_id <> d.id
条件。
修改强>
如果您没有唯一的列,但想要删除所有重复项(不保留至少一行),那么您可以使用:
DELETE d
FROM table_with_duplicates d
JOIN (
SELECT field
FROM table_with_duplicates
GROUP BY field
HAVING count(*) > 1
) del ON del.field = d.field;