删除具有两个特定列重复项的重复行

时间:2016-05-26 01:24:45

标签: php mysql

我正在尝试从我的数据库中删除重复的行,这些行具有相同的“输入”列和“响应”列。现在,我有一个查询SELECT所有重复项,但我不知道如何编写查询来删除重复项:

SELECT * , COUNT( * ) AS matches 
FROM allData 
GROUP BY input, response 
HAVING matches > 1 

如果我正在编写DELETE查询,我认为它会像

DELETE FROM allData WHERE blah = blah

^ ---但是这不允许我选择'count(*)'或'group by',所以我不确定如何正确地写这个。任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

试试这个;)

DELETE 
    T1
FROM allData T1
INNER JOIN (
    SELECT input, response
    FROM allData 
    GROUP BY input, response 
    HAVING COUNT(1) > 1 
) T2 ON T1.input = T2.input AND T1.response = T2.response

<强>编辑:

DELETE T1
FROM allData T1
INNER JOIN allData T2 ON T1.input = T2.input AND T1.response = T2.response AND T1.id > T2.id

这将保留具有最小ID的记录。 并查看Delete all duplicate rows except for one in mysql