A-A+

Mysql中如何查找并删除重复数据

2013年10月15日 MYSQL 暂无评论 阅读 2,479 次
如果您有代购或者代维服务器、PHP网站建设、程序代码修改、系统开发等需求,可以联系我购买付费服务。QQ 379880222

考试系统中做了一个用户导入试题功能,导致用户导入了很多重复的试题,我需要查询及删除一下重复的记录,于是有了这篇文章。

(一)单个字段

1、查找表中多余的重复记录,根据(question_title)字段来判断
select * from questions where question_title in (select question_title from people group by question_title having count(question_title) > 1)
2、删除表中多余的重复记录,根据(question_title)字段来判断,只留有一个记录
delete from questions
where peopleId in (select peopleId from people group by peopleId having count(question_title) > 1)
and min(id) not in (select question_id from questions group by question_title having count(question_title)>1)
(二)多个字段

删除表中多余的重复记录(多个字段),只留有rowid最小的记录
DELETE FROM questions WHERE (questions_title,questions_scope) IN (SELECT questions_title,questions_scope FROM questions GROUP BY questions_title,questions_scope HAVING COUNT(*) > 1) AND question_id NOT IN (SELECT MIN(question_id) FROM questions GROUP BY questions_scope,questions_title HAVING COUNT(*)>1)
用上述语句无法删除,创建了临时表才删的,求各位达人解释一下。
CREATE TABLE tmp AS SELECT question_id FROM questions WHERE (questions_title,questions_scope) IN (SELECT questions_title,questions_scope FROM questions GROUP BY questions_title,questions_scope HAVING COUNT(*) > 1) AND question_id NOT IN (SELECT MIN(question_id) FROM questions GROUP BY questions_scope,questions_title HAVING COUNT(*)>1);

DELETE FROM questions WHERE question_id IN (SELECT question_id FROM tmp);

DROP TABLE tmp;
(三)
declare @max integer,@id integer

declare cur_rows cursor local for select 主字段,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

标签:

给我留言