美文网首页Hive/Sql
leetcode(sql)196. Swap Salary

leetcode(sql)196. Swap Salary

作者: 马路仔 | 来源:发表于2019-06-27 10:28 被阅读0次

Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.

Person

Id Email
1 john@example.com
2 bob@example.com
3 john@example.com

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 john@example.com
2 bob@example.com

Note:Your output is the whole Person table after executing your sql. Use delete statement.(您的输出是执行sql之后的整个Person表。使用delete语句。)

DELETE p1
FROM
    Person as p1 JOIN Person as p2
WHERE
    p1.Email = p2.Email AND p1.Id > p2.Id;

通过在电子邮件列中将这个表与它自己连接起来,然后我们需要找到与其他记录具有相同电子邮件地址的较大id。所以我们可以像这样在WHERE子句中添加一个新的条件。因为我们已经得到了要删除的记录,所以我们可以最后将这个语句更改为DELETE

相关文章

网友评论

    本文标题:leetcode(sql)196. Swap Salary

    本文链接:https://www.haomeiwen.com/subject/sdklcctx.html