-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path196_Delete_Duplicate_Emails.py
96 lines (67 loc) · 2.13 KB
/
196_Delete_Duplicate_Emails.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""
196. Delete Duplicate Emails
Easy
280
334
Favorite
Share
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] |
+----+------------------+
Note:
Your output is the whole Person table after executing your sql. Use delete statement.
"""
"""
DELETE p1
FROM Person p1, Person p2
WHERE p1.Email = p2.Email AND
p1.Id > p2.Id
EXPLANATION:
Take the table in the example
Id | Email
Join the table on itself by the Email and you'll get:
FROM Person p1, Person p2 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] | 2 | [email protected]
1 | [email protected] | 3 | [email protected]
3 | [email protected] | 3 | [email protected]
From this results filter the records that have p1.Id>p2.ID, in this case you'll get just one record:
AND p1.Id > p2.Id
p1.Id | p1.Email | p2.Id | p2.Email
3 | [email protected] | 1 | [email protected]
This is the record we need to delete, and by saying
DELETE p1
in this multiple-table syntax, only matching rows from the tables listed before the FROM clause are deleted, in this case just
p1.Id | p1.Email
will be deleted
credit to fabrizio3, from https://leetcode.com/problems/delete-duplicate-emails/discuss/55553/Simple-Solution
"""
# Write your MySQL query statement below
DELETE p1
FROM Person as p1, Person as p2
WHERE p1.Email = p2.Email AND p1.Id > p2.Id;
"""
Success
Details
Runtime: 1089 ms, faster than 6.56% of MySQL online submissions for Delete Duplicate Emails.
Memory Usage: N/A
"""