LeetCode:. 196 Remove duplicate e-mail

Topic link: https: //leetcode-cn.com/problems/delete-duplicate-emails/

topic

Write a SQL query to delete Persontable all duplicate email, duplicate mailbox retain only Idthe 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 bywill solve the problem, but may be subject stated clearly, with the group bysubmission has not passed, a local test is estimated to be necessary requirements for deleteoperation, instead select.

---- MySQL ----
select min(Id) as Id,
       Email
from Person
group by Email; -- 简单 只是不通过

Refer to the official answer after answer.

Use deleteand whereclause 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 MySQLstill not familiar with the syntax oracleis somewhat different.

If the table name with the alias, delete the alias to add.

With a left jointry.

---- 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 selectbecause deleteand selectcan not operate on a table, it is added after the outer layer query produces a temporary table, this way you can deleteoperate.

Think

After self-ligation by determining the size of 2 id, then delete it.

Of deleteoperation is quite strange, after all, usually used more or selectoperations, only need to query data, ok.

Guess you like

Origin www.cnblogs.com/hider/p/11746422.html