Here is your original request
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) ;
From your comments, I understand it now
- Area can reach Access
- Access to the client, but you do not need
- Access can reach Course.CourseHistory via cusid.
Given this path, here is a refactored request
SELECT r.cusid FROM (SELECT realmid FROM Realms WHERE realmname = 'Course') r LEFT JOIN (SELECT realmid,cusid,accid FROM Access) a ON r.realmid=a.realmid LEFT JOIN (SELECT cusid FROM Course.CourseHistory) ch ON a.cusid=ch.cusid WHERE COALESCE(chid, accid);
You will need the following indexes
ALTER TABLE Realms ADD INDEX realmname_realmid_ndx (realmname,realmid); ALTER TABLE Access ADD INDEX realmid_cusid_accid_ndx (realmid,cusid,accid);
Give it a try !!!
source share