此題有兩個解法: 我初步嘗試用以下 解決問題(要刪除的記錄 肯定大於相同內容的 ): 但是無法通過,究其原因是在 語句中, 與`DELETE`操作不能同時存在. 答案一 因此嘗試新的解法,直接使用刪除語句,結果如下所示: 此答案通過測試,但是效率較低. 答案二 後續思考中發現,可以使用臨時表解決 與 ...
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
語句比較清晰明瞭.