【数据库查询】196. Delete Duplicate Emails

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jiang_1603/article/details/88042701

196. 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出来然后执行DELETE,这样居然不行,会报错“You can’t specify target table for update in FROM clause“,原因是在MYSQL中,不能先select一个表的记录,在按此条件进行更新和删除同一个表的记录。解决办法是,将select得到的结果,再通过中间表select一遍,这样就避免了错误,这个问题只出现于mysql,ms sql和oracle不会出现此问题。

# Write your MySQL query statement below
DELETE FROM Person
WHERE Id IN (SELECT a.Id FROM (
                SELECT p1.Id FROM Person p1, Person p2
                WHERE p1.Id > p2.Id AND p1.Email = p2.Email) AS a
             );


 

猜你喜欢

转载自blog.csdn.net/jiang_1603/article/details/88042701