Skip to content

Latest commit

 

History

History
69 lines (54 loc) · 1.44 KB

Delete Duplicate Emails.md

File metadata and controls

69 lines (54 loc) · 1.44 KB

Hint

Use a SELF JOIN

MySQL Solution

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

Example

Input:

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | [email protected] |
| 2  | [email protected]  |
| 3  | [email protected] |
+----+------------------+

The table after the implicit join and the WHERE p1.Email = p2.Email:

+-------+------------------+-------+------------------+
| p1.Id | p1.Email         | p2.Id | p2.Email
+-------+------------------+-------+------------------+
|   1   | [email protected] |   1   | [email protected] |
|   3   | [email protected] |   1   | [email protected] |
|   2   | [email protected]  |   1   | [email protected]  |
|   1   | [email protected] |   3   | [email protected] |
|   3   | [email protected] |   3   | [email protected] |
+-------+------------------+-------+------------------+

The following row matches the criteria of p1.Id > p2.Id:

In our original p1 table this row will be deleted:

Now p1 is our final table:

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | [email protected] |
| 2  | [email protected]  |
+----+------------------+

Links