In my query i want to join two tables based on the value of a field (say field1). Depending on the value of the field1 the join would EITHER be:
field3 = field4 OR field5 = field6
Something like
join on
CASE FIELD1
When 1 THEN FIELD 2 = FIELD3
When 2 THEN FIELD 4 = FIELD5
END
I am doing something like this at the moment
.... join on (field1=1 AND field2=field3) OR (field1=2 AND field4=field5)
but it takes ages to run the query. The two conditions individually take less than 7 secs each
How can i do this?
I would highly recommend against this approach. You are forcing the db to run a query it can’t do anything to optimise. Instead look at your tables and see if there isn’t something that can be done to split the data so this conditional isn’t needed.
Alternatively if you really need to do this then the fastest way to do it is run two queries and
unionthe results:This should be far faster.