这篇文章给大家分享的是有关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)bona.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<value);/*ERROR1093(HY000):Youcan'tspecifytargettable'a'forupdateinFROMclause*/目前,您不能从一个表中删除,同时又在子查询中从同一个表中选择。------------------删除特定重复行----------------主要通过orderby+limit或者直接limitcreatetabletest_3(idint,valueint);inserttest_3select1,2unionallselect1,3unionallselect1,4unionallselect2,3;--这是要保留ID=1value最小的那个记录,删除其他id为的记录deletefromtest_3whereid=1orderbyvaluedesclimit2;select*fromtest_3;+------+-------+|id|value|+------+-------+|1|2||2|3|+------+-------+如果你只想删除任意的记录保留一条就可以去掉orderby

感谢各位的阅读!关于“MySQL如何消除重复行”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!