Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

LEFT OUTER JOIN with SubQuery

lawarnerMay 29 2008 — edited May 30 2008
I have two tables and I want to return all data from the first table with a piece of information from the second based on an effective date being at least a certain value. The tables I am working with contain billions of rows so I need a solution that will also scale.

Sample tables:

create table pp ( x number, y number);

create table ec ( x number, y number, effdate date);

insert into pp values (1,2);
insert into pp values (2,3);
insert into pp values (1,3);

insert into ec values (1,2,sysdate);
insert into ec values (2,3,sysdate);
insert into ec values (1,3,sysdate+365);
commit;

select * from pp, ec where pp.x = ec.x(+) and pp.y=ec.y(+)
and (effdate = ( select max(effdate) from ec ecc where ecc.y=ec.y and ecc.x = ec.x and effdate < sysdate) or effdate is null);

The above query (and the one below) returns two rows. it does not return where the date does not meet the criteria.

select * from pp LEFT OUTER JOIN ec ON pp.x = ec.x and pp.y=ec.y
WHERE (effdate = ( select max(effdate) from ec ecc where ecc.y=ec.y and ecc.x = ec.x and effdate < sysdate) or effdate is null);

This returns the three rows BUT IS VERY SLOW when run against the billion+ row table (because we cannot correlate the subquery results.)

select * from pp LEFT OUTER JOIN (SELECT x, y, effdate
FROM ec WHERE effDate = (SELECT MAX(EFFdate) from ec ecc where ecc.y=ec.y and ecc.x = ec.x and effdate < sysdate)) c ON c.x = pp.x and c.y = pp.y;
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 27 2008
Added on May 29 2008
3 comments
1,934 views