为什么我需要运行此脚本两次以删除所有重复项?

时间:2013-08-29 21:45:10

标签: mysql sql

我所做的是创建一个名为Rent2的临时表来存放我的客户注册的所有重复模块,然后在删除临时表之前执行删除内部连接语句。

但完成后总会留下重复的内容。我在这里做错了什么?

CREATE  TABLE IF NOT EXISTS `tblRent2` (
  `IdRent` INT(11) NOT NULL)
ENGINE = InnoDB;

INSERT INTO tblRent2 (SELECT IdRent FROM tblRent WHERE IdModule = 1 GROUP BY IdClient HAVING COUNT(IdModule) > 1);
INSERT INTO tblRent2 (SELECT IdRent FROM tblRent WHERE IdModule = 2 GROUP BY IdClient HAVING COUNT(IdModule) > 1);
INSERT INTO tblRent2 (SELECT IdRent FROM tblRent WHERE IdModule = 3 GROUP BY IdClient HAVING COUNT(IdModule) > 1);
INSERT INTO tblRent2 (SELECT IdRent FROM tblRent WHERE IdModule = 4 GROUP BY IdClient HAVING COUNT(IdModule) > 1);
INSERT INTO tblRent2 (SELECT IdRent FROM tblRent WHERE IdModule = 5 GROUP BY IdClient HAVING COUNT(IdModule) > 1);
INSERT INTO tblRent2 (SELECT IdRent FROM tblRent WHERE IdModule = 6 GROUP BY IdClient HAVING COUNT(IdModule) > 1);
INSERT INTO tblRent2 (SELECT IdRent FROM tblRent WHERE IdModule = 999 GROUP BY IdClient HAVING COUNT(IdModule) > 1);

DELETE r.* FROM tblRent r INNER JOIN tblRent2 r2 ON 
r.idRent = r2.idRent;

SELECT * FROM tblRent2;

DROP TABLE tblRent2;

原始表格如下:

IdRent | IDClient  | IdModule
1      |  30       |   999
2      |  30       |   999
3      |  31       |   1
4      |  31       |   1

这些都是主键。

2 个答案:

答案 0 :(得分:5)

更好的问题是为什么使用临时表?

只需将表格加入自身:

DELETE r2
FROM tblRent r
JOIN tblRent r2
    ON r.IDClient = r2.IDClient
    AND r.IdModule = r2.IdModule
    AND r.idRent < r2.idRent

这也会清理一式三份,总是留下最低idRent的行。

一个关键点(原谅双关语)是额外的连接条件r.idRent < r2.idRent,它阻止行连接到它们自己(通过具有不等的ID),并选择最后添加的行进行删除(通过强制一个id到小于另一个)。使用r.idRent != r2.idRent会导致两个重复项被删除。

答案 1 :(得分:1)

我认为您的删除查询存在缺陷。删除后,删除关键字后不应要求使用星号。您可以使用此查询。

DELETE FROM tblRent WHERE idRent in (SELECT IdRent FROM tblRent2);