美文网首页
Leetcode_SQL-简单-196-删除重复的电子邮箱

Leetcode_SQL-简单-196-删除重复的电子邮箱

作者: Gaafung峰 | 来源:发表于2020-03-10 22:55 被阅读0次

问题

编写一个 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

提示:
执行 SQL 之后,输出是整个 Person 表。
使用 delete 语句。

准备

create database leecote196;


use leecote196;


create table Person (
id int(20),
Email varchar(20));


drop table Person;


insert into Person values
(1,'john@example.com'),
(2,'bob@example.com'),
(3,'john@example.com');

解答

SELECT p1.* FROM Person p1,Person p2
WHERE p1.Email = p2.Email AND p1.Id > p2.Id;


DELETE p1.* FROM Person p1,Person p2
WHERE p1.Email = p2.Email AND p1.Id > p2.Id;

相关文章

网友评论

      本文标题:Leetcode_SQL-简单-196-删除重复的电子邮箱

      本文链接:https://www.haomeiwen.com/subject/hhtodhtx.html