Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
+----+------------------+
Id is the primary key column for this table.
For example, after running your query, the above Person table should have the following rows:
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
+----+------------------+
Note:
Your output is the whole Person table after executing your sql. Use delete statement.
此題有兩個解法:
我初步嘗試用以下sql解決問題(要洗掉的記錄Id肯定大于相同內容的Id):
delete p1 from Person p1, Person p2 where p2.id > p1.id and p2.Email = p1.Email;
但是無法通過,究其原因是在sql陳述句中,SELECT與DELETE操作不能同時存在.
答案一
因此嘗試新的解法,直接使用洗掉陳述句,結果如下所示:
delete p1 from Person p1, Person p2 where p1.id > p2.id and p1.Email = p2.Email;
此答案通過測驗,但是效率較低.
答案二
后續思考中發現,可以使用臨時表解決SELECT與DELETE同時存在的問題,答案如下所示:
DELETE FROM Person
WHERE Id IN
(
SELECT Id FROM
(SELECT p1.Id as Id FROM Person p1, Person p2 WHERE p1.Email = p2.Email AND p1.Id > p2.Id) AS TEMP
)
此解決方案完美解決問題,且sql陳述句比較清晰明了.
PS:
如果您覺得我的文章對您有幫助,請關注我的微信公眾號,謝謝!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/119271.html
標籤:MySQL

