196. Delete Duplicate Emails
俗话说得好,人不会相同的地方第二次摔倒,我会。
DELETE FROM 表名 WHERE 条件;
那么条件如何确定,首先了解一下自连接.
用数据库实际操作一下,我们就能发现其原理:
这是初始的表格,接下来我们应用一下自连接:
这是应用了自连接之后的结果,自连接的语句如下:
SELECT * FROM table t1, table t2
可以看出,自连接其实就相当于是笛卡尔积。
参考:https://leetcode.com/problems/delete-duplicate-emails/solutions/2627589/my-sql-solution
Input: Person table: +----+------------------+ | id | email | +----+------------------+ | 1 | john@example.com | | 2 | bob@example.com | | 3 | john@example.com | +----+------------------+ => From Person p1, Person p2 : it would look like: 1|john@example.com|1|john@example.com 1|john@example.com|2|bob@example.com 1|john@example.com|3|john@example.com 2|bob@example.com|1|john@example.com 2|bob@example.com|2|bob@example.com 2|bob@example.com|3|john@example.com 3|john@example.com|1|john@example.com 3|john@example.com|2|bob@example.com 3|john@example.com|3|john@example.com => From Person p1, Person p2 where p1.email=p2.email and p1.id>p2.id: It would look like: 3|john@example.com|1|john@example.com Now delete this row's matching row in p1 using p1: delete p1