1 Star 0 Fork 0

zhaohui24 / Algorithms

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
LC196-删除重复的电子邮箱.md 1.94 KB
一键复制 编辑 原始数据 按行查看 历史
zhaohui24 提交于 2021-10-07 12:14 . update LC196.md.

编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。

Id Email
1 john@example.com
2 bob@example.com
3 john@example.com

Id 是这个表的主键。

例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:

Id Email
1 john@example.com
2 bob@example.com

法一: 使用 group by 进行连接

参考链接 - 一只猪的解题思路 - 及其Niyada 、17693410138评论

create TABLE LC196(Id int(10), Email VARCHAR(20));

insert into LC196 VALUES(1, 'john@example.com');
insert into LC196 VALUES(2, 'bob@example.com');
insert into LC196 VALUES(3, 'john@example.com');
insert into LC196 VALUES(4, 'bon@example.com');


-- 法一:使用group by, 再取min(id)

DELETE from LC196 a
where a.id not in 
(
	SELECT need.id from 
		(select min(id) as id
			from LC196
			GROUP BY email
		) as need
);


-- 使用 exists 优化
DELETE from LC196 a
where not exists
(
    select need.id from
    (
        select min(id) as id from LC196 GROUP BY email
    ) as need
    where need.id = a.id
);

参考链接 - 官方题解 - 删除重复的电子邮箱

-- 法二:自连接
-- 自连接
SELECT p1.*
FROM LC196 p1,
    LC196 p2
WHERE
    p1.Email = p2.Email

-- 找出重复的id大的值
SELECT p1.*
FROM LC196 p1,
    LC196 p2
WHERE
    p1.Email = p2.Email AND p1.Id > p2.Id;
		

-- 删除
DELETE p1 FROM LC196 p1,
    LC196 p2
WHERE
    p1.Email = p2.Email AND p1.Id > p2.Id;
1
https://gitee.com/zhaohui24/algorithm-problem.git
git@gitee.com:zhaohui24/algorithm-problem.git
zhaohui24
algorithm-problem
Algorithms
master

搜索帮助