Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[๋ฆฌํŠธ์ฝ”๋“œ] 196. Delete Duplicate Emails

์ธ” 2023. 1. 29. 23:32

๐Ÿ“ข ๋ณธ ํฌ์ŠคํŒ…์— ํ™œ์šฉ๋˜๋Š” ๊ธฐ๋ณธ ๋ฌธ์ œ ๋ฐ ์ž๋ฃŒ ์ถœ์ฒ˜๋Š”

       ๋ฆฌํŠธ์ฝ”๋“œ Problems / https://leetcode.com/problemset/all/  ์ž„์„ ๋ฐํž™๋‹ˆ๋‹ค.


โ–  ๋ฌธ์ œ

https://leetcode.com/problems/delete-duplicate-emails/description/

 

Delete Duplicate Emails - LeetCode

Delete Duplicate Emails - Table: Person +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | email | varchar | +-------------+---------+ id is the primary key column for this table. Each row of this table contains an em

leetcode.com

Table: Person

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| email       | varchar |
+-------------+---------+
id is the primary key column for this table.
Each row of this table contains an email. The emails will not contain uppercase letters.

 

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.

โ–  ํ’€์ด

  ๋ฌธ์ œ ์š”๊ตฌ์‚ฌํ•ญ  

๊ฐ€์žฅ ์ž‘์€ ID๋ฅผ ๊ฐ–๋Š” ๊ณ ์œ ํ•œ ์ „์ž ๋ฉ”์ผ์ด ๋˜๋„๋ก ์ค‘๋ณต๋˜๋Š” ์ด๋ฉ”์ผ์„ ์‚ญ์ œ.

SELECT๋ฌธ์ด ์•„๋‹Œ DELETE๋ฌธ์„ ์‚ฌ์šฉํ•  ๊ฒƒ > DELETE FROM ~

 

๋ฐฉ๋ฒ•1) email๋ณ„๋กœ ๊ทธ๋ฃนํ•‘ํ•ด์„œ ๊ฐ€์žฅ ์ž‘์€ id๋ฅผ ๊ฐ–๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ์ง€์›Œ์ง€์ง€ ์•Š๋„๋ก ์ถœ๋ ฅ

DELETE FROM person
 WHERE id NOT IN (
     SELECT T1.min_id
      FROM (SELECT email, MIN(id) min_id
             FROM person
             GROUP BY 1) T1)

 

๋ฐฉ๋ฒ•2) ์…€ํ”„ ์กฐ์ธ์œผ๋กœ ์ค‘๋ณต๋˜๋Š” ์ด๋ฉ”์ผ์˜ ๊ฒฝ์šฐ, ์•„์ด๋”” ์ˆซ์ž๊ฐ€ ํฐ ๋ฐ์ดํ„ฐ๋ฅผ ์‚ญ์ œ

DELETE P1
 FROM person P1
 INNER JOIN person P2
 ON P1.email = P2.email
 WHERE P1.id > P2.id