25 删除重复的电子邮箱
astak16 opened this issue · comments
柚子uccs commented
题目
删除 person
表中所有重复的电子邮箱,重复的邮箱只保留 id
最小的那个。
create table person (
id int,
email varchar(255)
)
insert into person values
(1, 'john@example.com'),
(2, 'bob@example.com'),
(3, 'john@example.com');
SQL:方法一
delete person from person
join person p2
on person.email = p2.email and person.id > p2.id;
解析
自连接,连接条件是 person.email = p2.email
筛选出 person.id > p2.id
,这个是要删除的。
SQL:方法二
delete person from person, person p2
where person.email = p2.email and person.id > p2.id;
解析
和方法一一样。
SQL:方法三
delete person from person,
(
select min(id) as id, email from person group by email having count(email) > 1) as p2
where person.email = p2.email and person.id != p2.id;
解析
- 将
person
安装email
进行分组,并用having
筛选出重复的最小id
- 将这个临时表在和
person
进行一起联查,条件是person.email = p2.email
并且不能和临时表的id
相同,结果就是要删除的数据。