Table: Person
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| email | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table contains an email. The emails will not contain uppercase letters.
Write a solution to delete all duplicate emails, keeping only one unique email with the smallest id.
For SQL users, please note that you are supposed to write a DELETE statement and not a SELECT one.
For Pandas users, please note that you are supposed to modify Person in place.
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 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.
해당 문제를 이제 풀려고 하는데
일단 첫번째로
SELECT MIN(ID),EMAIL
FROM PERSON
GROUP BY EMAIL
이걸 적었는데 전혀 먹히지 않더라...
그래서
DELETE문을 사용하려 했다.
DELETE FROM PERSON
WHERE ID = (SELECT MAX(ID) FROM PERSON GROUP BY EMAIL);
그런데 계속 RUNTIME ERROR가 나면
You can't specify target table 'PERSON' for update in FROM clause
이 오류 메시지를 보여주더라.
그래서 왜 그럴까??라고 알아본 결과
같은 테이블(Person)을 "삭제하려고 하면서 동시에 SELECT 서브쿼리에서도 읽어오는 것"을 금지한다고 한다.
DELETE를 하려는 대상을 FROM 절 안에서 직접 SELECT하고 있기 때문에 충돌(위험)이 생긴다고 본다고 한다.
즉 업데이트하려는 테이블과 읽으려는 테이블을 동일하게 사용하면 안된다는 규칙이 있다.
그럼 어떻게 해야할까?
DELETE p1
FROM PERSON p1
JOIN PERSON p2
ON p1.Email = p2.Email AND p1.Id > p2.Id;
다시 Person을 조인해서 p1과 p2 사이에서 같은 이메일을 찾고 p1.Id와 p2.Id를 비교해 p2.Id보다 큰 p1.Id를 찾아서
삭제 한다.
'Coding Test' 카테고리의 다른 글
조건에 맞는 사용자 정보 조회하기(SQL) [프로그래머스] (0) | 2025.03.15 |
---|---|
128. longest-consecutive-sequence(LeetCode) (0) | 2024.06.15 |
125. Valid Palindrome(LeetCode) (0) | 2024.06.03 |
217. Contains Duplicate(LeetCode) (2) | 2024.05.22 |
백준 1018번 문제(JAVA) 리뷰 (0) | 2023.02.14 |