๐ข ๋ณธ ํฌ์คํ ์ ํ์ฉ๋๋ ๊ธฐ๋ณธ ๋ฌธ์ ๋ฐ ์๋ฃ ์ถ์ฒ๋
๋ฆฌํธ์ฝ๋ 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
'Growth ๐ณ > Practice ๐ป' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฆฌํธ์ฝ๋] 596. Classes More Than 5 Students (0) | 2023.02.10 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค] ์๋์ฐจ ๋์ฌ ๊ธฐ๋ก๋ณ ๋์ฌ ๊ธ์ก ๊ตฌํ๊ธฐ (23.06.14 ์ฌํ์ด) (0) | 2023.01.30 |
[ํด์ปค๋ญํฌ] The Report (2) | 2023.01.29 |
[ํด์ปค๋ญํฌ] Top Earners (0) | 2023.01.29 |
[ํด์ปค๋ญํฌ] Weather Observation Station 16 (0) | 2023.01.28 |