Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

25 删除重复的电子邮箱 #30

Open
astak16 opened this issue Jan 14, 2022 · 0 comments
Open

25 删除重复的电子邮箱 #30

astak16 opened this issue Jan 14, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Jan 14, 2022

题目

删除 person 表中所有重复的电子邮箱,重复的邮箱只保留 id 最小的那个。

create table person (
	id int,
	email varchar(255)
)

insert into person values
(1, '[email protected]'),
(2, '[email protected]'),
(3, '[email protected]');

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 相同,结果就是要删除的数据。
@astak16 astak16 added the 简单 label Jan 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant