我想从下表中删除多个重复的键:
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查询来进行唯一的输入,因为我希望将这些重复的输入输入到表中。
unique constraint
一种方法是使用将表联接到子查询上LEFT JOIN。子查询得到最低ID为每UID。当记录在子查询上不匹配时,仅表示它没有匹配的记录并且可以安全地删除。
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。
name
group by
uid
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