I have a client table which with a foreign key to itself where each client has a specific id in each department but one master id. I am trying to find the most efficient way to restrict my query to just the master entry.
Here are the two (simplified) queries I have that work but I feel like there is a more efficient way to accomplish this especially when joining to other large tables:
-- version 1
select
client.id
from
client
join client client2 on client.id = client2.masterid
and client2.id = client2.masterid
--version 2
select
client.id,
from
client
where
client.id = client.masterid
-- Expanded view
select
t1.id masterid,
t1.dob dob,
trunc((months_between(trunc(sysdate),t1.dob)/12),0) age,
case
when substr(t1.zip,1,5) in ('48502','48503','48504','48505','48506','48507','48529','48532') then null
else
(select
max(audit1.operationid)
from
t2 audit1
where
t1.id = audit1.sourceid
and audit1.fieldname = 'ZIP'
and substr(audit1.oldvalue,1,5) in ('48502','48503','48504','48505','48506','48507','48529','48532')
and audit1.created >= to_date('04/25/2014', 'MM/DD/YYYY')
and 1 < (
select
count(audr.id)
from
t2 audr
WHERE
audr.operationid = audit1.operationid
and audr.fieldname in ('ADDRESS1','CITY')
)
) end auditref,
t1.address1 addr1,
t1.address2 addr2,
t1.city city,
substr(t1.zip,1,5) zip
from
t1
where
t1.id = t1.masterid
and 1 = case
when substr(t1.zip,1,5) in ('48502','48503','48504','48505','48506','48507','48529','48532') then 1
when substr(t1.zip,1,5) not in ('48502','48503','48504','48505','48506','48507','48529','48532') and exists
(select
1
from
t2 audit2
where
audit2.sourceid = t1.id
and audit2.fieldname = 'ZIP'
and substr(audit2.oldvalue,1,5) in ('48502','48503','48504','48505','48506','48507','48529','48532')
and audit2.created >= to_date('04/25/2014', 'MM/DD/YYYY')
) then 1
else 0
end
Any thoughts would be appreciated as any other ways I have tried these joins have caused duplicate rows as there can be many ids for each masterid.
Edit:
Here is a more expanded version of the query but there are more joins and filters being used where using the client.id = client.masterid is causing the query to run much slower
The question is the most effective way to limit the t1 and t2 table scans as these tables are huge...
Using the following join accomplished the goal of limiting the table scans: