删除数据库(ASE/ASA/Oracle)表中的重复行(小结)

本文介绍在ASE、ASA及Oracle等数据库中去除重复记录的方法,包括使用临时表和基于rowid的策略,适用于MySQL和DB2等其他数据库系统。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文为iihero原创,如若转载,请注明出处。谢谢。

为简化问题:

设表:t(id int, col2 varchar(32))

1. ASE:

选出重复的行:
select * from t group by id, col2 having count(*)>1

删掉重复的行,
alter table t add col3 int identity not null;
delete from t where col3 not in (select max(col3) from t group by id, col2);
alter table t drop col3;(前提select into/bulkcopy on数据库上的options)

2. ASA: (设表t123)

select * from t123

id,col2
1,'a'
1,'a'
2,'b'
3,'c'
delete from t123 where col3 not in (select max(col3) from t123 group by id, col2);
alter table t123 drop col3;

上述方法对ASE和ASA基本上是一样的。除了ASE中要求目标数据库select into为ON

3. ORACLE:

大概有两种方法:

方法1:基于rowid

delete from t a
where a.rowid !=
(
select max(b.rowid) from t b
where a.id = b.id and
a.col2 = b.col2
)

SQL> select * from t; ID COL2 ---------- -------------------------------- 1 a 1 a 2 b 3 c SQL> delete from t a where a.rowid != (select max(b.rowid) from t b where a.id=b.id and a.col2 = b.col2); 已删除 1 行。 SQL> select * from t; ID COL2 ---------- -------------------------------- 1 a 2 b 3 c

方法2:使用临时表

SQL> select * from t; ID COL2 ---------- -------------------------------- 1 a 2 b 3 c SQL> insert into t values(1, 'a'); 已创建 1 行。 SQL> create table tt as select t.id, t.col2, max(t.rowid) dataid from t group by t.id, t.col2; 表已创建。 SQL> delete from t a where a.rowid != (select b.dataid from tt b where a.id=b.id and a.col2=b.col2); 已删除 1 行。 SQL> select * from t; ID COL2 ---------- -------------------------------- 2 b 3 c 1 a

相信ASE/ASA也可以使用临时表的方案。(表特别大的时候,也许很有用)

至于MySQL/DB2当中的方法,应该是很类似的。不再赘述。

<script type="text/javascript"><!-- google_ad_client = "ca-pub-7104628658411459"; /* wide1 */ google_ad_slot = "8564482570"; google_ad_width = 728; google_ad_height = 90; //--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值