1. 程式人生 > 實用技巧 >MySQL關於資料表中刪除某一欄位的資料重複項的解決方案

MySQL關於資料表中刪除某一欄位的資料重複項的解決方案

步驟:

1.建立一個序列表並初始化資料

2.對有重複資料的欄位項進行列轉行

3.刪除列轉行後的重複記錄

4.用group_concat函式將需要去重的欄位項轉化成以逗號分隔的字串

5.對原表進行關聯更新

6.刪除去重資料建立的輔助表

一.建表,準備好初始資料

create table user1_practice(
id int not null auto_increment primary key,
user_name varchar(3),
`over` varchar(5),
mobile varchar(100));
insert into user1_practice(user_name,`over`,mobile) 
values ('唐僧','旃檀功德佛','12112345678,14112345678,12112345678'),
('豬八戒','淨壇使者','12144643321,14144643321'), 
('孫悟空','鬥戰勝佛','12166666666,14166666666,18166666666,18166666666'),
('沙僧','金身羅漢','12198343214,14198343214');

查看錶資料:select * from user1_practice;

在表中我們可以發現user_name為唐僧的mobile有兩條重複資料12112345678,user_name為孫悟空的mobile有兩條重複資料18166666666,下面按步驟來將這兩條記錄去重

二.建立一個序列表並初始化資料

create table tb_sequence(id int not null auto_increment primary key);
insert into tb_sequence values(),(),(),(),(),(),(),(),();

查看錶資料:select * tb_sequence;

此表只包含了一串自增id序列號

三.列轉行後的表user1_trans1(user1_practice)

create table user1_trans1 as 
select a.id,user_name,`over`,replace(substring(
substring_index(mobile,',',a.id),
char_length(substring_index(mobile,',',a.id-1))+1),',','') as mobile 
from tb_sequence a 
cross join(select user_name,`over`,concat(mobile,',') as mobile,
length(mobile)-length(replace(mobile,',',''))+1 as size 
from user1_practice b) b on a.id <= b.size;

查看錶資料:select * from user1_trans1;

四.刪除user1_trans1表中的重複記錄

delete a from user1_trans1 a 
join (select user_name,`over`,mobile,count(*),max(id) as id 
from user1_trans1  
group by user_name,`over`,mobile having count(*) > 1  ) b
on a.user_name = b.user_name and a.`over` = b.`over` and a.mobile = b.mobile 
where a.id < b.id;

查看錶資料:select * from user1_trans1;

五.用group_concat函式將mobile轉化成以逗號分隔的字串

create table user1_trans2 as 
select user_name,`over`,group_concat(mobile) as mobile 
from user1_trans1 group by user_name,`over`;

查看錶資料:select * from user1_trans2;

六.對原表user1_practice進行關聯更新

update user1_practice a 
inner join user1_trans2 b on a.user_name = b.user_name
set a.mobile = b.mobile; 

查看錶資料:select * from user1_practice;

七.刪除tb_sequence,user1_trans1,user1_trans2等輔助表

drop table tb_sequence;
drop table user1_trans1;
drop table user1_trans2;

此文來源於慕課網:https://www.imooc.com/video/8281