Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to outer join a sub query

Status
Not open for further replies.

bookouri

IS-IT--Management
Feb 23, 2000
1,464
US
I have run into this same problem a couple of times. Since I cant outer join on a subquery, is there some way to work around it? For example something like:

select e.last_name, r.address, r.address_seq
from
employees e, residences r
where e.emp_id=r.emp_id
and r.address_seq = (select max(address_seq) from residences r2 where e.emp_id=r2.emp_id)

in this case we use address_seq to identify the most recent address on file. The problem occurs when the target has no residences on file. Normally I would outer join at "r.address_seq =" to get all records, but Oracle does not allow an outer join here.

Can anybody give me any suggestions how to work around this kind of problem?

thanks in advance
 
I would do a union

select e.last_name, r.address, r.address_seq
from
Do the following....

employees e, residences r
where e.emp_id=r.emp_id
and r.address_seq = (select max(address_seq) from residences r2 where e.emp_id=r2.emp_id)

union

select e.last_name, NULL, NULL
from
employees e
where not exists (select *
from residence r1
where r1.emp = e.emp)

-lw
 
...and you can do it with a single query (without a UNION):
Code:
select e.last_name, r.address, r.address_seq
  from employees e, residences r
 where e.emp_id=r.emp_id(+)
   and (r.address_seq is null
        or r.address_seq =
           (select max(address_seq)
              from residences r2
             where e.emp_id = r2.emp_id(+))
       )
/
Let us know how either of these techniques works for you.

[santa]Mufasa
(aka Dave of Sandy, Utah, USA)
[I provide low-cost, remote Database Administration services: www.dasages.com]
 
The outer join will work also by making the subquery an inline view.

select e.last_name, r.address, r.address_seq
from
employees e
left outer join
( -- make inline view of max addresses
select
max(address_seq) as address_seq,
emp_id
from residences r2
group by emp_id
) vw
on vw.emp_id = e.emp_id
left outer join residences r
on e.emp_id=r.emp_id
and vw.address_seq = r.address_seq
 
Thanks for the replies. I decided to use mufasa's example this time. But, Im going to work with both the other techniques. I never use unions and really need to understand them better. I have used inline code similar to cmmrfrds example before on something like this, but i had completely forgotten about it.

Thanks again for the suggestions.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top