This is a bit of a weird question, so the best way to ask it is with an example. I have a list of customers. I want to get any customer who has a corresponding entry in either the CourseHistory
table or the Access
table (or both).
I want an optimal single query (no subqueries) that fetches these customers. I came up with
SELECT
c.cusid
FROM
Customers c
CROSS JOIN Realms r
LEFT JOIN Course.CourseHistory ch ON (c.cusid = ch.cusid)
LEFT JOIN Access a ON (c.cusid = a.cusid AND r.realmid = a.realmid)
WHERE
realmname = 'Course'
AND COALESCE(chid, accid)
This works but it is noticeably slow, probably because it has to do a full scan of Customers
. Since either CourseHistory
or Access
can be null and the result still be valid, they have to be left joined. Is there a more correct way to do this query?