views:

53

answers:

3

I probably didn't word the question right buy I have a query that is taking a substantial amount of time because of 'or'.

select stuff 
from table1 T1
left join table2 T2 on T2.field1 = T1.field or T2.field2 = T1.field
where some condition

I have to check both fields to join. Is there a better way to do this?

+3  A: 

There's two options I can think of based on what's provided:

Use IN instead

   select stuff 
     from table1 T1
left join table2 T2 on T1.field IN (T2.field1, T2.field2)
    where some condition

Using a UNION

Mind that I used UNION ALL--it's faster than UNION, but UNION removes duplicates so alter to suit your needs:

   select stuff 
     from table1 T1
left join table2 T2 on T1.field = T2.field1
    where some condition
UNION ALL
   select stuff 
     from table1 T1
left join table2 T2 on T1.field = T2.field2
    where some condition
OMG Ponies
I tried it and I get the same result unfortunately.
Eric
@Eric: Then you'll have to provide actual detail for us to diagnose the performance issue.
OMG Ponies
I used Union instead of Union all. Seems to give me the results i needed.
Eric
+2  A: 

If you follow the rule either T2.field1 = T1.field true or T2.field2 = T1.field. when output depends on atleast one is true.

**select stuff 
from table1 T1, table2 T2 
where some condition AND (T2.field1 = T1.field or T2.field2 = T1.field)**
AsifQadri
brackets do not improve performance; they only ensure order of operations.
OMG Ponies
A: 

You could use T1.field IN (T2.field1, T2.field2) but I doubt it will improve your query performance.

Alin Purcaru