gpt4 book ai didi

MySQL 删除 with where 不会报错

转载 作者:行者123 更新时间:2023-11-29 12:17:32 24 4
gpt4 key购买 nike

我有一个这样的表:

create table person (
id integer,
Email varchar(100)
);


insert into person values (1, 'john@example.com');
insert into person values (2, 'bob@example.com');
insert into person values (3, 'john@example.com');
insert into person values (4, 'john@example.com');

现在,我需要删除重复行并保留最小 Id,这意味着删除后表将是:

+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
+----+------------------+

我得到这个是为了获取一个不重复的 id 列表:

select Id from Person group by Email;

删除代码是:

delete from Person
where Person.Id not in
(select Id from Person group by Email);

但对我来说不起作用,为什么我不能这样写以及如何解决它?

最佳答案

您可以使用 JOIN as 轻松完成

delete p from person p 
join (
select min(id) as id ,email from person group by email
)p1
on p1.id < p.id and p1.Email = p.Email ;

关于MySQL 删除 with where 不会报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29540100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com