3

我想从下表中删除多个重复键:

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查询来制作唯一的条目,因为我希望将这些重复的条目输入到表格中。

4

2 回答 2

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可以有不同的名称,那么您需要包含namegroup by子句中,否则只会保留uid最低的唯一性ID

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
于 2013-03-20T06:01:46.000 回答
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;
于 2013-03-20T06:02:30.200 回答