Mysql中查找并删除重复数据的方法

  次阅读 来源:互联网(转载协议) 2016-01-28 13:00 我要评论(0)

(一)单个字段

1、查找表中多余的重复记录,根据(question_title)字段来判断

代码如下

select * from questions where question_title in (select question_title from peoplegroup 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

例,

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

例1,表中有主键(可唯一标识的字段),且该字段为数字类型

例1测试数据

代码如下

/* 表结构 */

DROP TABLE IF EXISTS `t1`;

CREATE TABLE IF NOT EXISTS `t1`(

`id` INT(1) NOT NULL AUTO_INCREMENT,

`name` VARCHAR(20) NOT NULL,

`add` VARCHAR(20) NOT NULL,

PRIMARY KEY(`id`)

)Engine=InnoDB;

/* 插入测试数据 */

INSERT INTO `t1`(`name`,`add`) VALUES

('abc',"123"),

本站部分文章来源于网络以及网友投稿,本站只负责对文章进行整理、排版、编辑,是出于传递更多信息之目的,并不意味着赞同其观点或证实其内容的真实性。如果您有什么意见或建议,请联系QQ28-1688-302!

人工智能实验室
相关文章相关文章
  • 让AI触手可及  Qualcomm携手创通联达推出全新终端侧AI开发套件

    让AI触手可及 Qualcomm携手创通联达推出全新终端侧AI开发套件

  • 品友互动为Digital Travel APAC2018 唯一受邀中国AI企业

    品友互动为Digital Travel APAC2018 唯一受邀中国AI企业

  • 长虹新款智能语音空调,告诉你空调也能玩Siri

    长虹新款智能语音空调,告诉你空调也能玩Siri

  • 第一批国家重点研发计划公布,旷视科技开启“五年行动”

    第一批国家重点研发计划公布,旷视科技开启“五年行动”

网友点评网友点评
阅读推荐阅读推荐

据外媒报道,STEER打造了首款完全自动驾驶停车技术,旨在使常规车辆转变为无人驾驶车辆。STEER的首款技术应用是4级自动驾驶及网络安全停车...

近日,美国软性机器抓手制造商 Soft Robotics 宣布,获得 2000 万美元的融资,本轮投资者包括 Scale Venture Partners,Calibrate Ventures...

据外媒报道,加州车管局发布了《2017自动驾驶脱离报告(California Autonomous Vehicle Disengagement Reports)》,其中谈及了脱离的具体...

用人机语音交互,来解决智能家居适老的问题;通过家庭门禁与安防套件、空气净化套件、可燃气体与有害气体监控套件等相互联动,在不同生活情...