我想从下表中删除多个重复的密钥:
id | name | uid
1 | ekta | 5
2 | ekta | 5
3 | sharma | 10
4 | sharma | 10
希望它像
id | name | uid
1 | ekta | 5
3 | sharma | 10
我正在使用mysql。可能吗?
我无法使用unique constraint
查询来创建唯一的输入,因为我希望将这些重复的条目输入到表中。
答案 0 :(得分:5)
这样做的一种方法是使用LEFT JOIN
在子查询上加入表。每个ID
子查询得到最低UID
。如果记录在子查询中没有匹配,则只表示它没有匹配的记录,可以安全删除。
DELETE a
FROM TableName a
LEFT JOIN
(
SELECT uid, MIN(ID) min_ID
FROM TableName
GROUP BY uid
) b ON a.uid = b.uid AND
a.ID = b.min_ID
WHERE b.uid IS NULL
但是,如果UID
的记录可以有不同的名称,那么您需要在name
子句中包含group by
,或者只包含uid
唯一ID
{ {1}}将保留。
DELETE a
FROM TableName a
LEFT JOIN
(
SELECT uid, MIN(ID) min_ID, name
FROM TableName
GROUP BY uid, name
) b ON a.uid = b.uid AND
a.ID = b.min_ID AND
a.name = b.name
WHERE b.uid IS NULL
答案 1 :(得分:0)
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;