删除数据库表中的重复记录

时间:2021-06-11 22:16:45

oracle

delete from  gcfr_t_vch_delete E WHERE E.rowid < (SELECT max(X.rowid) 
FROM gcfr_t_vch_delete X WHERE X.vchno = E.vchno and e.type = x.type and e.curragency = x.curragency);
--或者
delete from  gcfr_t_vch_delete E WHERE E.rowid > (SELECT min(X.rowid) 
FROM gcfr_t_vch_delete X WHERE X.vchno = E.vchno and e.type = x.type and e.curragency = x.curragency);

以凭证的类型,编号,单位为判断重复的依据。删除重复的就是要删除多余的并且只留下一条。上述sql的意思就是查出重复的记录之后,以一个最大值为标准,把小于他的都删掉。或者以最小的为标准,把大于他的都删掉。这样就正好满足需求。

oracle利用rowid来保证数据的唯一性,其实用一个表字段也可以,但是要保证这个字段的唯一性,最好是主键。

mysql

delete from  gcfr_t_vch_delete E WHERE E.guid < (SELECT max(X.guid) 
FROM gcfr_t_vch_delete X WHERE X.vchno = E.vchno and e.type = x.type and e.curragency = x.curragency);
--或者
delete from  gcfr_t_vch_delete E WHERE E.guid > (SELECT min(X.guid) 
FROM gcfr_t_vch_delete X WHERE X.vchno = E.vchno and e.type = x.type and e.curragency = x.curragency);

mysql这里没有rowid,以guid为例,guid是表的主键。