SQL實(shí)現(xiàn)LeetCode(196.刪除重復(fù)郵箱)
[LeetCode] 196.Delete Duplicate Emails 刪除重復(fù)郵箱
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 | john@example.com |
| 2 | bob@example.com |
| 3 | john@example.com |
+----+------------------+
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 | john@example.com |
| 2 | bob@example.com |
+----+------------------+
這道題讓我們刪除重復(fù)郵箱,那我們可以首先找出所有不重復(fù)的郵箱,然后取個(gè)反就是重復(fù)的郵箱,都刪掉即可,那么我們?nèi)绾握页鏊胁恢貜?fù)的郵箱呢,我們可以按照郵箱群組起來(lái),然后用Min關(guān)鍵字挑出較小的,然后取補(bǔ)集刪除即可:
解法一:
DELETE FROM Person WHERE Id NOT IN (SELECT Id FROM (SELECT MIN(Id) Id FROM Person GROUP BY Email) p);
我們也可以使用內(nèi)交讓兩個(gè)表以郵箱關(guān)聯(lián)起來(lái),然后把相同郵箱且Id大的刪除掉,參見代碼如下:
解法二:
DELETE p2 FROM Person p1 JOIN Person p2 ON p2.Email = p1.Email WHERE p2.Id > p1.Id;
我們也可以不用Join,而直接用where將兩表關(guān)聯(lián)起來(lái)也行:
解法三:
DELETE p2 FROM Person p1, Person p2 WHERE p1.Email = p2.Email AND p2.Id > p1.Id;
類似題目:
Duplicate Emails
參考資料:
https://leetcode.com/discuss/61176/simple-solution-using-a-self-join
https://leetcode.com/discuss/48403/my-answer-delete-duplicate-emails-with-double-nested-query
到此這篇關(guān)于SQL實(shí)現(xiàn)LeetCode(196.刪除重復(fù)郵箱)的文章就介紹到這了,更多相關(guān)SQL實(shí)現(xiàn)刪除重復(fù)郵箱內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。