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] | +----+------------------+
编写一个 SQL 查询,来删除
Person
表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。
+----+------------------+ | Id | Email | +----+------------------+ | 1 | [email protected] | | 2 | [email protected] | | 3 | [email protected] | +----+------------------+ Id 是这个表的主键。
例如,在运行你的查询语句之后,上面的 Person
表应返回以下几行:
+----+------------------+ | Id | Email | +----+------------------+ | 1 | [email protected] | | 2 | [email protected] | +----+------------------+
517ms
1 DELETE 2 FROM person 3 WHERE id NOT IN (SELECT t.id 4 FROM ( 5 SELECT min(id) AS id 6 FROM Person 7 GROUP BY email 8 ) t);
500ms
1 # Write your MySQL query statement below 2 DELETE 3 FROM Person 4 WHERE Id IN ( 5 SELECT Id 6 FROM ( 7 SELECT 8 Id, Email, (Email = @prev) AS dup, @prev := Email 9 FROM ( 10 SELECT Email, Id 11 FROM Person 12 ORDER BY 1, 2 13 ) AS sorted, 14 (SELECT @prev := NULL) AS init 15 ) AS t 16 WHERE dup IS TRUE 17 )
505ms
1 # Write your MySQL query statement below 2 delete from Person where Id not in(select t.Id from (select min(Id) id from Person b group by Email) t)
原文地址:https://www.cnblogs.com/strengthen/p/9744408.html
时间: 2024-10-09 02:13:13