有两个表,tparent和tchild,它们是使用脚本#1创建的。 需要查询两个表中uname等于'sky'的所有信息。 当只有少数记录时,以下查询语句#2很快。 但是,当使用以下脚本#3插入大量记录时,它将变得非常缓慢。 我认为它是由表之间的OR条件引起的,索引将无法用于查询。 所以我得到了一个快速的解决方案,将语句改为三个子组和联合结果,如#4。 我想知道有更好的解决方案吗?那是什么?
谢谢!
#1
drop table tparent;
drop table tchild;
create table tparent(typeid int,sno number,uname varchar2(50) );
create table tchild(typeid int,sno number,seqno int,uname varchar2(50));
create unique index uidx_tparent_typeidsno on tparent(typeid,sno);
create unique index uidx_tchild_typeidsnoseqno on tchild(typeid,sno,seqno);
create index idx_tparent_name on tparent(uname);
create index idx_tchild_name on tchild(uname);
insert into tparent values (1,10,'lily');
insert into tparent values (1,11,'eric');
insert into tparent values (2,10,'tom');
insert into tparent values (2,11,'eric');
insert into tparent values (3,10,'sky');
insert into tchild values (1,10,1,'sam');
insert into tchild values (1,10,2,'sky');
insert into tchild values (1,11,1,'eric');
insert into tchild values (1,11,2,'john');
insert into tchild values (2,10,1,'sky');
insert into tchild values (2,11,1,'eric');
insert into tchild values (3,10,1,'tony');
#2
select p.typeid,p.sno,p.uname,c1.uname as uname1,c2.uname as uname2 from tparent p
left join tchild c1 on c1.typeid=p.typeid and c1.sno = p.sno and c1.seqno=1
left join tchild c2 on c2.typeid=p.typeid and c2.sno = p.sno and c2.seqno=2
where (p.uname='sky' or c1.uname='sky' or c2.uname='sky');
#3
BEGIN
FOR x IN 1..10
LOOP
BEGIN
FOR y IN 10000..100000
LOOP
BEGIN
insert into tparent values (x,y,'name'|| y);
insert into tchild values (x,y,1,'name'|| y);
insert into tchild values (x,y,2,'name'|| y);
END;
END LOOP;
COMMIT;
END;
END LOOP;
END;
#4
select typeid,sno,max(uname),max(uname1),max(uname2) from (
select p.typeid,p.sno,p.uname,c1.uname as uname1,c2.uname as uname2 from tparent p
left join tchild c1 on c1.typeid=p.typeid and c1.sno = p.sno and c1.seqno=1
left join tchild c2 on c2.typeid=p.typeid and c2.sno = p.sno and c2.seqno=2
where (p.uname='sky' )
union
select p.typeid,p.sno,p.uname,c1.uname as uname1,c2.uname as uname2 from tparent p
left join tchild c1 on c1.typeid=p.typeid and c1.sno = p.sno and c1.seqno=1
left join tchild c2 on c2.typeid=p.typeid and c2.sno = p.sno and c2.seqno=2
where ( c1.uname='sky' )
union
select p.typeid,p.sno,p.uname,c1.uname as uname1,c2.uname as uname2 from tparent p
left join tchild c1 on c1.typeid=p.typeid and c1.sno = p.sno and c1.seqno=1
left join tchild c2 on c2.typeid=p.typeid and c2.sno = p.sno and c2.seqno=2
where ( c2.uname='sky')
) tb group by typeid,sno
order by typeid,sno
;
答案 0 :(得分:0)
你应该在你的子句中使用“union all”然后分组。