【Leetcode Database】Delete Duplicate Emails
2015-06-11 10:43
399 查看
题目:
Write a SQL query to delete all duplicate email entries in a table named
keeping only unique emails based on its smallest Id.
For example, after running your query, the above
should have the following rows:
第一次尝试代码:
select * from Person group by Email;发现可以分组但是没有排序,因此加一个order by即可
原表:
查询结果:
第二次尝试代码:
select * from Person group by Email order by Id;
在自己的机器上通过,结果在Leetcode上报错。
刚开始还以为是版本的问题,我的是5.7,Leetcode是5.5。
后来仔细审题才发现,是自己审题出错了。题目要求写SQL语句删除Person表中的重复数据(Write a SQL query
to delete all duplicate email entries in a table named
第三次尝试代码:
只要删除内部的重复Email即可,使用内连接,加p1.Email=p2.Email和p1.Id>p2.Id两个条件,即可删除p1中的重复记录。
验证通过。
本题知识点:
(1)删和查的概念不要搞混;
(2)内连接。
Write a SQL query to delete all duplicate email entries in a table named
Person,
keeping only unique emails based on its smallest Id.
+----+------------------+ | Id | Email | +----+------------------+ | 1 | john@example.com | | 2 | bob@example.com | | 3 | john@example.com | +----+------------------+ Id is the primary key column for this table.
For example, after running your query, the above
Persontable
should have the following rows:
+----+------------------+ | Id | Email | +----+------------------+ | 1 | john@example.com | | 2 | bob@example.com | +----+------------------+
第一次尝试代码:
select * from Person group by Email;发现可以分组但是没有排序,因此加一个order by即可
原表:
查询结果:
第二次尝试代码:
select * from Person group by Email order by Id;
在自己的机器上通过,结果在Leetcode上报错。
刚开始还以为是版本的问题,我的是5.7,Leetcode是5.5。
后来仔细审题才发现,是自己审题出错了。题目要求写SQL语句删除Person表中的重复数据(Write a SQL query
to delete all duplicate email entries in a table named
Person, ),而我之前所做的仅仅是查询而已。
第三次尝试代码:
delete p1 from Person p1, Person p2 where p1.Email=p2.Email and p1.Id>p2.Id;
只要删除内部的重复Email即可,使用内连接,加p1.Email=p2.Email和p1.Id>p2.Id两个条件,即可删除p1中的重复记录。
验证通过。
本题知识点:
(1)删和查的概念不要搞混;
(2)内连接。
相关文章推荐