避免在表格中重复记录
我有一张如下表所示的表
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
答案 0 :(得分: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 Fiddle 强>
然后继续你应该添加一个唯一索引来阻止进一步的重复。
CREATE UNIQUE INDEX UQ_Models ON Models (Model_No);
答案 1 :(得分:2)
delete m from models m
join models m2 on m2.model_no = m.model_no and m.model_id > m2.model_id
答案 2 :(得分: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);
答案 3 :(得分:0)
试试这个:
ALTER IGNORE TABLE `models`
ADD UNIQUE INDEX (`model_no`);