Oracle单表去重复(二)
时间:2014-05-01 11:13:53
收藏:0
阅读:555
Oracle单表去重
去重有两层含义,一:是记录完全一样。二:是符合一定条件的认为是重复。
根据表的数量,去重可划分为:单表去重和多表关联去重。
对于去重,一般最容易想到的是用distinct,而distinct只能对记录完全重复的记录保留一条。
distinct使用的是二重循环的方式来去重的,如果数据量非常大的时候,会导致性能急剧下降。
我们前一篇文章已经给出了详解,你可以去查看 Oracle单表去重复(一)
下面是一个单表去重的测试,认为name字段相同的即为重复记录,要查询出一个结果,过滤掉重复,distinct显然不能满足要求。
表SQL:
create table A_TEST
(
id number,
name varchar2(20),
remark varchar2(20)
);
insert into A_TEST (ID, NAME, REMARK)
values (1, ‘a‘, ‘ss‘);
insert into A_TEST (ID, NAME, REMARK)
values (2, ‘b‘, ‘xxx‘);
insert into A_TEST (ID, NAME, REMARK)
values (3, ‘b‘, ‘x‘);
insert into A_TEST (ID, NAME, REMARK)
values (4, ‘b‘, ‘asd‘);
insert into A_TEST (ID, NAME, REMARK)
values (5, ‘c‘, ‘axxx‘);
insert into A_TEST (ID, NAME, REMARK)
values (6, ‘c‘, ‘asdf‘);
(
id number,
name varchar2(20),
remark varchar2(20)
);
insert into A_TEST (ID, NAME, REMARK)
values (1, ‘a‘, ‘ss‘);
insert into A_TEST (ID, NAME, REMARK)
values (2, ‘b‘, ‘xxx‘);
insert into A_TEST (ID, NAME, REMARK)
values (3, ‘b‘, ‘x‘);
insert into A_TEST (ID, NAME, REMARK)
values (4, ‘b‘, ‘asd‘);
insert into A_TEST (ID, NAME, REMARK)
values (5, ‘c‘, ‘axxx‘);
insert into A_TEST (ID, NAME, REMARK)
values (6, ‘c‘, ‘asdf‘);
去重方式一(低效):
select a.*
from A_TEST a, (select min(id) as id from A_TEST t group by name) b
where a.id = b.id;
from A_TEST a, (select min(id) as id from A_TEST t group by name) b
where a.id = b.id;
去重方式一(高效):
select *
from (select a.*, rownum row_num from A_TEST a) x
where x.row_num in (select min(rownum) from A_TEST t group by name)
from (select a.*, rownum row_num from A_TEST a) x
where x.row_num in (select min(rownum) from A_TEST t group by name)
可见,使用rownum的效率比使用id的效率要高,当表数据量很大的时候,差距会很明显。
评论(0)