您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

MySQL查询重复记录sql语句

2024/5/18 3:58:06发布26次查看
在数据开发时我们常常会需要把数据库中重复的记录查出来或直接删除数据库中重复记录,下面我来给大家总结一些方法,有需要的朋友可参考。
常用的语句
1、查找表中多余的重复记录,重复记录是根据单个字段(mail_id)来判断
 代码如下 复制代码
 select * from table where mail_id in (select mail_id from table group by mail_id having count(mail_id) > 1);
2、删除表中多余的重复记录,重复记录是根据单个字段(mail_id)来判断,只留有rowid最小的记录
 代码如下 复制代码
delete from table where mail_id in (select mail_id from table group by mail_id having count(mail_id) > 1) and rowid not in (select min(rowid) from table group by mail_id having count(mail_id )>1);
3、查找表中多余的重复记录(多个字段)
 代码如下 复制代码
select * from table where (mail_id,phone) in (select mail_id,phone from table group by mail_id,phone having count(*) > 1);
4、删除表中多余的重复记录(多个字段),只留有rowid最小的记录
 代码如下 复制代码
 delete from table where (mail_id,phone) in (select mail_id,phone from table group by mail_id,phone having count(*) > 1) and rowid not in (select min(rowid) from table group by mail_id,phone having count(*)>1);
5、查找表中多余的重复记录(多个字段),不包含rowid最小的记录
 代码如下 复制代码
select * from table where (a.mail_id,a.phone) in (select mail_id,phone from table group by mail_id,phone having count(*) > 1) and rowid not in (select min(rowid) from table group by mail_id,phone having count(*)>1);
存储过程
 代码如下 复制代码
declare @max integer,@id integer
declare cur_rows cursor local for 主字段,count(*) from 表名 group by 主字段 having count(*) >; 1
open cur_rows
fetch cur_rows into @id,@max
while @@fetch_status=0
begin
select @max = @max -1
set rowcount @max
delete from 表名 where 主字段 = @id
fetch cur_rows into @id,@max
end
close cur_rows
set rowcount 0
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product