表: Person
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| email | varchar |
+-------------+---------+
id是该表的主键列。
该表的每一行包含一封电子邮件。电子邮件将不包含大写字母。
编写一个 SQL 删除语句来 删除 所有重复的电子邮件,只保留一个id最小的唯一电子邮件。
以 任意顺序 返回结果表。 (注意: 仅需要写删除语句,将自动对剩余结果进行查询)
查询结果格式如下所示。
示例 1:
输入:
Person 表:
+----+------------------+
| id | email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
+----+------------------+
输出:
+----+------------------+
| id | email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
+----+------------------+
解释: [email protected]重复两次。我们保留最小的Id = 1。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/delete-duplicate-emails
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
--------------------------------------------------------------------------------------------------
简单题一点都不简单。。。
官解是这样的:
DELETE p1 FROM Person p1, Person p2 WHERE p1.Email = p2.Email AND p1.Id > p2.Id 作者:LeetCode 链接:https://leetcode.cn/problems/delete-duplicate-emails/solution/shan-chu-zhong-fu-de-dian-zi-you-xiang-by-leetcode/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
这样虽然代码看起来简洁,但会产生笛卡尔积,需要尽量避免。
可以采用子查询的方式
# Please write a DELETE statement and DO NOT write a SELECT statement. # Write your MySQL query statement below delete from Person where id not in( select id from( select min(id) as id from Person group by email )p );
标签:力扣,196,example,---,Person,+----+------------------+,email,com,id From: https://www.cnblogs.com/allWu/p/17081190.html