如何刪除表中的重複記錄並只保留一條
創建表
# 創建一個表
drop table if exists student;
create table student(
id int(11) auto_increment,
name varchar(100) not null,
classroom int(11) not null,
primary key(id)
) Engine = InnoDB,default charset=utf8;
插入測試數據
insert into student(name,classroom) values("小明",101),("小華",103),("小明",101),("小明",101),("小明",104),("小紅",102),("小林",105),("小華",102),("小華",105);
插入之後表的數據如下所示:
查詢所有重複記錄
查詢所有人名相同的重複記錄
select * from student where name in (select name from student group by name having count(name)>1);
運行結果如下所示:
查詢所有多餘的重複記錄(除rowid最小的那條記錄)
查找出所有人名相同的多餘重複記錄(根據id來判斷,除了rowid最小的那條)
- 方法一:
select * from student where
name in (select name from student group by name having count(name)>1) and
id not in(select min(id) from student group by name having count(name)>1);
條件主要有兩點必須同時滿足:
(1)是重複記錄;
(2)除去重複記錄中的第一條記錄;
- 方法二:效率比方法一更高一點
select * from student where id not in (select stu.minid from (select min(id) as minid from student group by name) stu);
運行結果如下所示:
刪除所有多餘的重複記錄(除rowid最小的那條記錄)
刪除所有人名相同的多餘重複記錄(根據id來判斷,除了rowid最小的那條)
- 方法一:
delete from student where
name in (select stu.name from (select name from student group by name having count(name)>1) stu)
and
id not in (select stu.minid from (select min(id) as minid from student group by name having count(name)>1) stu);
注意這裏不能是將對應的查詢方法一直接將select * 改爲 delete得到,這樣的話會出現
You can’t specify target table ‘dept’ for update in FROM clause 錯誤,因爲你不能同時對同一個表進行查詢和更新。
所以多使用了一層select語句,這樣外層查詢的是臨時表,而不是原表,而刪除的是原表,所以這樣就不會出現這種錯誤。
- 方法二:
delete from student where id not in (select stu.minid from (select min(id) as minid from student group by name) stu);
運行之後,表的數據如下所示:
刪除單個字段的重複記錄會了,則可以舉一反三地學會刪除多個字段的重複記錄。