mysql删除某一列值重复的全部行和只留一条

https://blog.csdn.net/evilcry2012/article/details/78819444

(1)mysql 数据库中删除某一列值重复的全部行(一个笔试题)

如果要求是多个字段重复的就在group后把所有要求重复的字段写上去

表名:zp

数据如下(都是int型的 sal:工资)

要求删除sal列中重复的数据的全部行,即结果如下图:

说下我的思路吧:

主要分为3步:(1)select sal,count(sal) salcount from zp group by sal //按sal分组

运行结果:

+------+----------+
| sal  | salcount |
+------+----------+
| 22.2 |        3 |
| 88.8 |        1 |
| 99.9 |        1 |
+------+----------+

(2)select t.sal from ((select sal,count(sal) salcount from zp group by sal) as t) where  t.salcount>1//找出分组后salcount大于1的sal值 

运行结果:

+----+
| sal   |
+----+
|  22.2 |
+-----+

(3)delete from zp where sal in(select t.sal from ((select sal,count(sal) salcount from zp group by sal) as t) where  t.salcount>1);//从zp表中删除sal满足第二步结果的所有行

ok:查询一下结果出现了哈哈

mysql> select * from zp ;
+----+------+
| id | sal  |
+----+------+
|  4 | 88.8 |
|  5 | 99.9 |
+----+------+

(2)只留一行

表名:fatie 

要求:删除name字段中值相同的重复行,且只留一行重复数据

 删除前(原表)如下:

删除后:

删除语句:delete from fatie where id not in(select t.id1 from ( (select max(a.id) id1 from fatie a group by a.name)as t));留下的是各组id号最大的,如果留的是最小的话换成min(a.id)就行了

如果没有加上一个中间表t,即这句话 select t.id from去掉直接写成delete from fatie where id not in(select max(id) a.id1 from fatie a group by a.name);mysql会提示错误:You can't specify target table 'fatie' for update in FROM clause (不能先select出同一表中的某些值,再update这个表(在同一语句中)。这和文章上面的问题一样,也是加了个中间表才可以),网上是这样说的:也就是说将select出的结果再通过中间表select一遍,这样就规避了错误。注意,这个问题只出现于mysql,mssql和oracle不会出现此问题。

这样感觉效率会很低的吧,请教大神高效率的sql

猜你喜欢

转载自blog.csdn.net/NRlovestudy/article/details/85316781