一、DELETE语法

1、删除整个表

delete from 表名;      

 2、删除满足筛选条件的行

delete 别名 from 表名 as 别名 where 筛选条件;
#尽量把条件包在where子句中

二、LEECODE196.删除重复的电子邮箱——使用delete

编写一个SQL查询来 删除 所有重复的电子邮件,只保留一个id最小的唯一电子邮件。

查询结果格式如下所示。

示例 1:

输入: 
Person 表:
+----+------------------+
| id | email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+
输出: 
+----+------------------+
| id | email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/delete-duplicate-emails
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 

方法一:

找出每个email的最小id,将其他删除即可

delete from person where id not in(
    select min(id) as id from person group by email);

注意:上面 代码会报错"You can't specify target table 'person' for update in FROM clause",因为MYSQL不允许同一张表一边查自己一边更新自己,可以使用select子句进行包装

delete from person where id not in(
    select id from(
        select min(id) as id 
        from person 
        group by email) as a);

方法二:

1、先对两个person表内连接,别名分别为a,b

连接条件为  a.id < b.id AND a.email = b.email     连接结果如下

 2、根据题目要求,a表删除这条数据删除即可。代码为

delete a from person as a, person as b 
where a.id > b.id and a.email = b.email

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐