mysql rowid踢重_rowid去重(删除表的重复记录)

-- 构造测试环境

SQL> create table andy(id int,name varchar2(10));

Table created.

SQL>

insert into andy values(1,'a');

insert into andy values(2,'b');

insert into andy values(3,'c');

insert into andy values(4,'d');

SQL> select * from andy;

ID NAME

---------- ----------

1 a

2 b

3 c

4 d

4 rows selected.

SQL>

insert into andy values(4,'f');

insert into andy values(4,'d');

SQL> select * from andy;

ID NAME

---------- ----------

1 a

2 b

3 c

4 d

4 f

4 d

6 rows selected.

-- 依次group by 表所有字段,通过min(rowid)查看所有唯一记录(去重记录,也就是相同多行数据只显示一行)

SQL> select id,name,min(rowid)

from andy

group by id,name;

ID NAME MIN(ROWID)

---------- ---------- ------------------

3 c AAAfKTAAEAAACr/AAC

4 d AAAfKTAAEAAACr/AAD

4 f AAAfKTAAEAAACr/AAJ

1 a AAAfKTAAEAAACr/AAA

2 b AAAfKTAAEAAACr/AAB

-- delete 重复数据时,group by 表的个别字段,发现误删除

SQL> delete from andy

where rowid not in (

select min(rowid)

from andy

group by id);

2 rows deleted.

说明:记录 4 f 被误删。

SQL> select * from andy;

ID NAME

---------- ----------

1 a

2 b

3 c

4 d

-- 构造与上面测试相同环境,即插入刚删除的数据

SQL>

insert into andy values(4,'f');

insert into andy values(4,'d');

SQL> select * from andy;

ID NAME

---------- ----------

1 a

2 b

3 c

4 d

4 f

4 d

6 rows selected.

-- 依次group by 表所有字段,通过min(rowid)查看所有唯一记录(去重记录,也就是相同多行数据只显示一行)

SQL> select id,name,min(rowid)

from andy

group by id,name;

ID NAME MIN(ROWID)

---------- ---------- ------------------

3 c AAAfKTAAEAAACr/AAC

4 d AAAfKTAAEAAACr/AAD

4 f AAAfKTAAEAAACr/AAL

1 a AAAfKTAAEAAACr/AAA

2 b AAAfKTAAEAAACr/AAB

-- delete 重复数据时,group by 表的所有字段,发现没有误删。

SQL> delete from andy

where rowid not in (

select min(rowid)

from andy

group by id,name);

1 row deleted.

-- 检查去重后的数据,发现没有误删

SQL> select * from andy;

ID NAME

---------- ----------

1 a

2 b

3 c

4 d

4 f

说明:

如果想通过rowid去重,那么在 delete 重复数据时,需要group by 表的所有字段。如果只group by 表的个别字段,那么会造成误删除。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值