有一個表user,字段分別有id、nick_name、password、email、phone。
一、單字段(nick_name)
查出所有有重復(fù)記錄的所有記錄
select * from user where nick_name in (select nick_name from user group by nick_name having count(nick_name)>1);
查出有重復(fù)記錄的各個記錄組中id最大的記錄
select * from user where id in (select max(id) from user group by nick_name having count(nick_name)>1);
查出多余的記錄,不查出id最小的記錄
select * from user where nick_name in (select nick_name from user group by nick_name having count(nick_name)>1) and id not in (select min(id) from user group by nick_name having count(nick_name)>1);
刪除多余的重復(fù)記錄,只保留id最小的記錄
delete from user where nick_name in (select nick_name from (select nick_name from user group by nick_name having count(nick_name)>1) as tmp1) and id not in (select id from (select min(id) from user group by nick_name having count(nick_name)>1) as tmp2);
二、多字段(nick_name,password)
查出所有有重復(fù)記錄的記錄
select * from user where (nick_name,password) in (select nick_name,password from user group by nick_name,password where having count(nick_name)>1);
查出有重復(fù)記錄的各個記錄組中id最大的記錄
select * from user where id in (select max(id) from user group by nick_name,password where having count(nick_name)>1);
查出各個重復(fù)記錄組中多余的記錄數(shù)據(jù),不查出id最小的一條
select * from user where (nick_name,password) in (select nick_name,password from user group by nick_name,password having count(nick_name)>1) and id not in (select min(id) from user group by nick_name,password having count(nick_name)>1);
刪除多余的重復(fù)記錄,只保留id最小的記錄
delete from user where (nick_name,password) in (select nick_name,password from (select nick_name,password from user group by nick_name,password having count(nick_name)>1) as tmp1) and id not in (select id from (select min(id) id from user group by nick_name,password having count(nick_name)>1) as tmp2);
以上就是MySQL 數(shù)據(jù)查重、去重的實現(xiàn)語句的詳細(xì)內(nèi)容,更多關(guān)于MySQL 數(shù)據(jù)查重、去重的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:- MySQL使用show status查看MySQL服務(wù)器狀態(tài)信息
- Mysql中 show table status 獲取表信息的方法
- mysql建表常用的sql語句匯總
- 記一次MySQL更新語句update的踩坑
- Navicat Premium操作MySQL數(shù)據(jù)庫(執(zhí)行sql語句)
- MySQL兩種刪除用戶語句的區(qū)別(delete user和drop user)
- MySQL 數(shù)據(jù)庫 like 語句通配符模糊查詢小結(jié)
- mysql中寫判斷語句的方法總結(jié)
- MySQL 常用的拼接語句匯總
- MySQL SHOW STATUS語句的使用