Topic link: https: //leetcode-cn.com/problems/delete-duplicate-emails/
topic
Write a SQL query to delete Person
table all duplicate email, duplicate mailbox retain only Id
the smallest one.
+ ---- + ------------------ +
| Id | Email |
+ ---- + -------------- + ----
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
+ ---- + ------------ + ------
Id is the primary key of this table.
For example, after you run the query, the Person table above should return the following lines:
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
+----+------------------+
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/delete-duplicate-emails
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
answer
I began to feel very simple, ah, group by
will solve the problem, but may be subject stated clearly, with the group by
submission has not passed, a local test is estimated to be necessary requirements for delete
operation, instead select
.
---- MySQL ----
select min(Id) as Id,
Email
from Person
group by Email; -- 简单 只是不通过
Refer to the official answer after answer.
Use delete
and where
clause answers.
---- MySQL ----
# Write your MySQL query statement below
delete a from Person a,
Person b
where a.Email = b.Email
and a.Id > b.Id ---- 707ms
For MySQL
still not familiar with the syntax oracle
is somewhat different.
If the table name with the alias, delete the alias to add.
With a left join
try.
---- MySQL ----
delete a from Person a
left join Person b
on a.Email = b.Email
where a.Id > b.Id; ---- 726ms
By delete
+ sub-queries, and more efficient.
---- MySQL ----
delete from Person
where Id not in
(
select Id
from
(
select min(Id) as Id
from Person
group by Email
) b
); ---- 506ms
Cadogan layer select
because delete
and select
can not operate on a table, it is added after the outer layer query produces a temporary table, this way you can delete
operate.
Think
After self-ligation by determining the size of 2 id, then delete it.
Of delete
operation is quite strange, after all, usually used more or select
operations, only need to query data, ok.