标签:leetcode
SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.
Id | |
---|---|
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 Person table should have the following rows:
Id | |
---|---|
1 | john@example.com |
2 | bob@example.com |
# 思路
题目的意思是:从Person表中找出Email重复的记录,只保留Id最小的记录,删除其他的重复记录。
因为是先查找,再删除,所以我们也分两步进行:
select p1.Id from Person as p1 inner join Person as p2 where p1.Email = p2.Email and p1.ID > p2.ID;
delete from Person where Id in ($sql1);
思路虽然是好的,但是这样写却是错误的:
delete from Person where Id in (select p1.Id from Person as p1 inner join Person as p2 where p1.Email = p2.Email and p1.ID > p2.ID);
错误信息为:
You can‘t specify target table ‘Person‘ for update in FROM clause
意思是:在MYSQL中,禁止在from子句中指定被更新的目标表。
所以,需要使用MYSQL规定的delete语法:
delete t1 from t1,t2 where t1.id = t2.id;
or
delete from t1 using t1,t2 where t1.id = t2.id;
delete t1 from t1 left join t2 on t1.id=t2.id where t2.id is null;
delete p1 from Person as p1 inner join Person as p2 on p1.ID > p2.ID and p1.Email = p2.Email;
[LeetCode]DeleteDuplicateEmails,解题报告
标签:leetcode
原文地址:http://blog.csdn.net/wzy_1988/article/details/45093645