leetcode 196. Delete Duplicate Emails

196. Delete Duplicate Emails

 
Question Editorial Solution
  My Submissions
  • Total Accepted: 15426
  • Total Submissions: 81201
  • Difficulty: Easy

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  | [email protected] |
| 2  | [email protected]  |
| 3  | [email protected] |
+----+------------------+
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 | Email            |
+----+------------------+
| 1  | [email protected] |
| 2  | [email protected]  |
+----+------------------+

Subscribe to see which companies asked this question

简单解法:

# Write your MySQL query statement below
delete p1
from Person p1, Person p2 
where p1.Email=p2.Email and p1.Id>p2.Id

另一种速度较快解法:

delete from 
Person
where  
Id not in (select Id 
           from 
            (select min(Id) as Id 
             from Person 
             group by Email
            ) p
          );



你可能感兴趣的:(leetcode,mysql,select,oj)