題目:
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上報錯。
Person
, ),而我之前所做的僅僅是查詢而已。delete p1 from Person p1, Person p2 where p1.Email=p2.Email and p1.Id>p2.Id;