I have a complex query. The following below is the most basic example of what I want to do.
SELECT
match_by_color AS match_type,
t1.*
FROM t1
WHERE
( t1.color LIKE 'color%') -- match_by_color
OR (t1.type in (select type from t2)) -- match_by_type
OR (t1.name in (select name from t3 WHERE ...)) -- match_by_name
OR (t1.age in (select age from t4 WHERE ...)) -- match_by_age
I have 3-4 conditions for matching a record. And if it matches on one of the conditions I want to identify the first matching type without running the sub queries again. I could do something like this but I feel like it would be running the same queries twice.
-- I could do this but it would be running the conditional sub queries twice
(
CASE
WHEN ( t1.color LIKE 'color%') THEN match_by_color
WHEN (t1.type in (select type from t2)) THEN match_by_color
WHEN (t1.name in (select name from t3 WHERE ...)) THEN match_by_name
WHEN (t1.age in (select age from t4 WHERE ...)) THEN match_by_age
ELSE no_match
END
) AS match_type
2
Answers
try this, I followed @nbk advice I also removed all the where clause to simplify, I guess it will perform better this way.
The problem with oversimplified questions about a "complex query" is that we are not aware of the complexities, which will inevitably have an impact on the best way to approach a query.
If the relationships between
t1
and each oft2
,t3
andt4
return 0 or 1 row then it is worth testingLEFT JOIN
:If the relationships may return more than 1 row, then try using
EXISTS(...)
: