[LeetCode] 196. Delete Duplicate Emails

주연·2023년 2월 7일
0

SQL 문제 풀이

목록 보기
2/28
post-thumbnail

230207

문제

Write an SQL query to delete all the duplicate emails, keeping only one unique email with the smallest id. Note that you are supposed to write a DELETE statement and not a SELECT one.

After running your script, the answer shown is the Person table. The driver will first compile and run your piece of code and then show the Person table. The final order of the Person table does not matter.

The query result format is in the following example.

Example 1:

Input:
Person table:
+----+------------------+
| id | email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
| 3 | john@example.com |
+----+------------------+
Output:
+----+------------------+
| id | email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
+----+------------------+
Explanation: john@example.com is repeated two times. We keep the row with the smallest Id = 1.

풀이

  • 서브쿼리 사용
DELETE 
FROM Person 
WHERE id NOT IN ( --keeping smallest id
    SELECT sub.min_id 
    FROM (
        SELECT email, MIN(id) min_id
        FROM Person
        GROUP BY email
    ) AS sub
)
  • JOIN 사용 (풀이 확인)
DELETE p1
FROM Person p1
    INNER JOIN Person p2 ON p1.email = p2.email
WHERE p1.id > p2.id
profile
공부 기록

0개의 댓글