【Leetcode Database】Delete Duplicate Emails

題目:

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]  |
+----+------------------+


第一次嘗試代碼:

select * from Person group by Email;
發現可以分組但是沒有排序,因此加一個order by即可

原表:



查詢結果:


第二次嘗試代碼:

select * from Person group by Email order by Id;

在自己的機器上通過,結果在Leetcode上報錯。


剛開始還以爲是版本的問題,我的是5.7,Leetcode是5.5。
後來仔細審題才發現,是自己審題出錯了。題目要求寫SQL語句刪除Person表中的重複數據(Write a SQL query to delete all duplicate email entries in a table named Person, ),而我之前所做的僅僅是查詢而已。

第三次嘗試代碼:
delete p1 from Person p1, Person p2 where p1.Email=p2.Email and p1.Id>p2.Id;
只要刪除內部的重複Email即可,使用內連接,加p1.Email=p2.Email和p1.Id>p2.Id兩個條件,即可刪除p1中的重複記錄。
驗證通過。

本題知識點:
(1)刪和查的概念不要搞混;
(2)內連接。













發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章