[LeetCode] DeleteDuplicateEmails, solution report, leetcode

Source: Internet
Author: User

[LeetCode] DeleteDuplicateEmails, solution report, leetcode
Question

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 Person table shocould have the following rows:

Id Email
1 John@example.com
2 Bob@example.com

#Ideas

The meaning of the question is: Find the repeated Email records from the Person table, only keep the records with the smallest Id, and delete other Repeated Records.

Because the search is performed first and then deleted, we have two steps:

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);

Although the idea is good, it is wrong to write it like this:

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);

Error message:

You can't specify target table 'Person' for update in FROM clause

In MYSQL, it is forbidden to specify the target table to be updated in the from clause.

Therefore, you need to use the delete syntax specified by MYSQL:

delete t1 from t1,t2 where t1.id = t2.id;ordelete 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;
AC SQL
delete p1 from Person as p1 inner join Person as p2 on p1.ID > p2.ID and p1.Email = p2.Email;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.