mysql删除重复记录
PHPz
PHPz 2017-04-17 13:33:39
[MySQL讨论组]

表由三个字段组成 id name type 关键是当时没设主键,现在有很多重复的数据,我可以用select distinct看到筛选后的数据,但不知道怎么把重复的删掉,希望大家能帮帮忙,谢谢!

PHPz
PHPz

学习是最好的投资!

全部回复(1)
ringa_lee
-- 原始表
create table ttd(
id varchar(30) not null,
name varchar(30) not null,
type int
);
insert into ttd(id, name, type) values ('a', 'na1', 1), ('b', 'nb1', 3), ('a', 'na1', 4), ('c', 'nc1', 1);

select * from ttd;

-- 臨時表1
create table tmp1(
s serial, -- 自增
id varchar(30) not null,
name varchar(30) not null,
type int
);
-- 將原始表數據插入到臨時表1
insert into tmp1 (id, name, type) (select id, name, type from ttd);

-- 創建臨時表2, 插入去重的數據
create table tmp2 as (
-- 因爲 id 都是相同的, 就取 tmp1 自增最大的那個至, 去除相同的 id
select t1.id, t1.name, t1.type from tmp1 as t1
right join (
select max(s) as ms, id from tmp1 group by id
) as t2 on t1.id=t2.id and t1.s=t2.ms
);

-- 刪除原始表
drop table ttd;
-- 創建新的表
create table ttd(
id varchar(30) not null,
name varchar(30) not null,
type int,
primary key(id) -- 加入主鍵
);
-- 將去重後的 tmp2 數據寫入到 新加的 ttd 表中
insert into ttd(id, name, type) (select * from tmp2);

-- 刪除臨時表
drop table tmp1;
drop table tmp2;
select * from ttd;
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号