我的表名是虚拟的,它包含6列,其中ID,NAME,TIMESTAMP和其他3列。
我想删除ID,NAME和TIMESTAMP值与其他行匹配的重复行。如果有多个具有相同ID,NAME和TIMESTAMP值的行,则保留一个并删除其他行。
答案 0 :(得分:0)
这是解决方案
https://stackoverflow.com/a/5016434
我刚刚遇到的另一种可能的解决方案:
DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name
如果要保留行ID最低的值OR
DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name
https://stackoverflow.com/a/5770309
DELETE DupRows.*
FROM MyTable AS DupRows
INNER JOIN (
SELECT MIN(ID) AS minId, col1, col2
FROM MyTable
GROUP BY col1, col2
HAVING COUNT(*) > 1
) AS SaveRows ON SaveRows.col1 = DupRows.col1 AND SaveRows.col2 = DupRows.col2
AND SaveRows.minId <> DupRows.ID;
答案 1 :(得分:0)
这是一个示例代码。这将有助于你完成它。
DELETE duplicate_rows.*
FROM dummy AS duplicate_rows
INNER JOIN (
SELECT MIN(id) AS id, name, timestamp
FROM dummy
GROUP BY session_id, user_id, category_id
HAVING COUNT(*) > 1
) AS unique_rows
ON unique_rows.session_id = duplicate_rows.session_id
AND unique_rows.user_id = duplicate_rows.user_id
AND unique_rows.category_id = duplicate_rows.category_id
AND unique_rows.id <> duplicate_rows.id;
您在此处找到更详细的说明:http://mildcoder.com/delete-duplicate-rows-from-a-mysql-table/