1

避免表中重复记录

我有一张像下面这样的表

CREATE TABLE models(model_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
                         model_no varchar(255));                             

INSERT INTO models(model_no)
                 VALUES('M24'),
                       ('M22'),
                       ('M25'),
                       ('M24'),
                       ('M24'),              
                       ('M35'),
                       ('M15'),
                       ('M18'),
                       ('M25'),
                       ('M15'),
                       ('M15'),
                       ('M17'),
                       ('M19'),
                       ('M29'),
                       ('M29'),
                       ('M12'),
                       ('M12'),
                       ('M13'),
                       ('M29');

我想通过运行删除或更新查询从该表中删除重复的模型,以便该模型将只出现一次,如下所示

1    M24
2    M22
3    M25
6    M35
7    M15
8    M18
12   M17
13   M19
14   M29
16   M12
18   M13
4

4 回答 4

2

要删除表中已存在的重复项,您可以使用:

CREATE TEMPORARY TABLE tmp (ModelID INT NOT NULL);

INSERT tmp (ModelID)
SELECT  t1.Model_ID
FROM    Models t1
WHERE   EXISTS
        (   SELECT  1
            FROM    Models t2
            WHERE   t1.Model_No = t2.Model_No
            AND     t2.Model_ID < t1.Model_ID
        );

DELETE  
FROM    Models
WHERE   Model_ID IN (SELECT ModelID FROM tmp);

SQL小提琴

然后继续前进,您应该添加一个唯一索引以阻止进一步的重复。

CREATE UNIQUE INDEX UQ_Models ON Models (Model_No);
于 2012-12-31T11:30:31.347 回答
2
delete m from models m
join models m2 on m2.model_no = m.model_no and m.model_id > m2.model_id
于 2012-12-31T11:42:48.377 回答
1

尝试使用临时表。

create temporary table tmpTable (model_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
                     model_no varchar(255));



 insert  tmpTable
    (model_id)
 select  model_id
 from    models m
 where   exists
    (
    select  *
    from   models m2
    where   m2.model_no = m.model_no

            and m2.model_id> m.model_id
    );

delete  
from    models
where   model_id in (select model_id from tmpTable);
于 2012-12-31T11:31:00.500 回答
0

试试这个:

ALTER IGNORE TABLE `models`   
ADD UNIQUE INDEX (`model_no`);
于 2012-12-31T11:33:44.603 回答