建站软件 优化软件 编程软件 网页辅助 站群程序 网站程序 图像处理 资源教程 字体下载 推荐软件


您的位置:首页 > MYSQL学习 > Mysql怎么查找重复数据并删除

Mysql怎么查找重复数据并删除

时间:2015-05-07 09:18:31  来源:免费模板网 作者:风雪 阅读次数 tagsmysql去重

有时候编辑在添加文章的时候弄重复了,或者表里面有重复的数据,但是页面不需要显示重复的数据怎么处理呢
(一)单个字段

1、查找表中多余的重复记录,根据question_title字段来判断,代码如下:

  1. select * from questions where question_title in (select question_title from people group by question_title having count(question_title) > 1) 

2、删除表中多余的重复记录,根据question_title字段来判断,只留有一个记录,代码如下:

  1. delete from questions 
  2. where peopleId in (select peopleId from people group by peopleId having count(question_title) > 1) 
  3. and min(id) not in (select question_id from questions group by question_title having count(question_title)>1)  

(二)多个字段

删除表中多余的重复记录,多个字段,只留有rowid最小的记录,代码如下:

  1. 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) 

用上述语句无法删除,创建了临时表才删的,求各位达人解释一下,代码如下:

  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); 
  2.  
  3. DELETE FROM questions WHERE question_id IN (SELECT question_id FROM tmp); 
  4.  
  5. DROP TABLE tmp; 

(三) 存储过程,代码如下:

  1. declare @max integer,@id integer 
  2.  
  3. declare cur_rows cursor local for select 主字段,count(*) from 表名 group by 主字段 having count(*) >; 1 
  4.  
  5. open cur_rows 
  6.  
  7. fetch cur_rows into @id,@max 
  8.  
  9. while @@fetch_status=0 
  10.  
  11. begin 
  12.  
  13. select @max = @max -1 
  14.  
  15. set rowcount @max 
  16.  
  17. delete from 表名 where 主字段 = @id 
  18.  
  19. fetch cur_rows into @id,@max 
  20.  
  21. end 
  22.  
  23. close cur_rows 
  24.  
  25. set rowcount 0 

例,数据库版本 Server version: 5.1.41-community-log MySQL Community Server (GPL).

本文地址:https://www.freemoban.com/mysql/2015/0507/1760.html

猜你喜欢
栏目推荐
模板推荐

Copyright:www.freemoban.com 免费模板网 All Rights Reserved 网站备案:辽ICP备19014872号-2   辽公网安备 21010602000376号  辽公网安备:42900402000182号

免责声明:本站部分资源来自互联网收集,版权归原创者所有,如果侵犯了你的权益,我们会及时删除侵权内容,联系QQ:1615187561 谢谢合作!