196. Delete Duplicate Emails
문제
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.
풀이
DELETE
FROM person
WHERE id NOT IN(
SELECT sub.min_id
FROM(
SELECT email
,MIN(id) AS min_id
FROM person
GROUP BY email
) sub )
# 서브쿼리 사용
# DELETE의 WHERE절 : 지울 데이터를 거르는 조건 -> NOT IN 사용
+) JOIN을 활용한 풀이
DELETE p1
FROM person p1
INNER JOIN person p2 ON p1.email = p2.email
WHERE p1.id > p2.id'SQL > LeetCode' 카테고리의 다른 글
| [SQL] LeetCode: 180. Consecutive Numbers (0) | 2023.06.23 |
|---|---|
| [SQL] LeetCode: 184. Department Highest Salary (0) | 2023.06.08 |
| [SQL] LeetCode: 627. Swap Salary (0) | 2023.06.07 |
| [SQL] LeetCode: SELF JOIN 문제 (0) | 2023.05.31 |
| [SQL] LeetCode : LEFT JOIN 문제 (0) | 2023.05.31 |