测试用例sql如下:
-- 创建表
create table t_user(
id int(11) not null primary key auto_increment,
user_name varchar(50) not null,
tel varchar(11) not null);
-- 插入测试数据
insert into t_user(user_name,tel) values('Jack', '13510078222');
insert into t_user(user_name,tel) values('Mark', '13510078111');
insert into t_user(user_name,tel) values('Lorry', '13510078222');
思路:
创建一张临时表(只有一个id字段)用于保存需要保留的id,然后通过group by
子句和min
函数找出需要保留的id并插入到临时表中,最后使用not in
子句将id不在临时表中的那些数据删除即可。
sql如下:
create table t_user_temporary(
id int(11) not null
);
insert into t_user_temporary select a.id from (select min(id) as id from t_user group by tel) a
delete from t_user where id not in (select id from t_user_temporary);