MySQL 消除重复行的一些方法
sql语句
/* MySQL消除重复行的一些方法 ---ChuMinfei ---2010-08-1222:49:44.660 --引用转载请注明出处:http://blog.csdn.NET/feixianxxx */ ----------------全部字段重复------------------------ --1使用表替换来删除重复项 createtabletest_1(idint,valueint); inserttest_1select1,2unionallselect1,2unionallselect2,3; --建立一个和源表结构一样的空的临时表 createtabletmpliketest_1; --向临时表插入不重复的记录 inserttmpselectdistinct*fromtest_1; --删除原表 droptabletest_1; --更改临时表名为目标表 renametabletmptotest_1; --显示 mysql>select*fromtest_1; +------+-------+ |id|value| +------+-------+ |1|2| |2|3| +------+-------+ --2.添加auto_increment属性列(这个方法只能用于MyISAM或者BDB引擎的表) createtabletest_1(idint,valueint)engine=MyISAM; inserttest_1select1,2unionallselect1,2unionallselect2,3; altertabletest_1addid2intnotnullauto_increment, addprimarykey(id,value,id2); select*fromtest_1; +----+-------+-----+ |id|value|id2| +----+-------+-----+ |1|2|1| |1|2|2| |2|3|1| +----+-------+-----+ deletefromtest_1whereid2<>1; altertabletest_1dropid2; select*fromtest_1; +----+-------+ |id|value| +----+-------+ |1|2| |2|3| +----+-------+ -------------------部分字段重复--------------------- --1.加索引的方式 createtabletest_2(idint,valueint); inserttest_2select1,2unionallselect1,3unionallselect2,3; AlterIGNOREtabletest_2addprimarykey(id); select*fromtest_2; +----+-------+ |id|value| +----+-------+ |1|2| |2|3| +----+-------+ 我们可以看到13这条记录消失了 我们这里也可以使用Unique约束因为有可能列中有NULL值,但是这里NULL就可以多个了.. --2.联合表删除 createtabletest_2(idint,valueint); inserttest_2select1,2unionallselect1,3unionallselect2,3; deleteAfromtest_2ajoin(selectMAX(value)asv,IDfromtest_2groupbyid)b ona.id=b.idanda.value<>b.v; select*fromtest_2; +------+-------+ |id|value| +------+-------+ |1|3| |2|3| +------+-------+ --3.使用Increment_auto也可以就是上面全部字段去重的第二个方法 --4.容易错误的方法 --有些朋友可能会想到子查询的方法,我们来试验一下 createtabletest_2(idint,valueint); inserttest_2select1,2unionallselect1,3unionallselect2,3; deleteafromtest_2awhereexists(select*fromtest_2wherea.id=idanda.value