I have one table service_contacts which can contain listids from the lists table and contactids from the contacts table. contact_list_relationship has the relationships between contacts and lists tables.
I’m trying to pull all the contacts which could be in a contactid in service_contacts, or in a listid (which each list contains contactids).
SELECT d.* FROM service_contacts a
LEFT JOIN lists b
ON a.calllistid=b.listid
LEFT JOIN contact_list_relationship c
ON c.listid=b.listid
INNER JOIN contacts d
ON d.contactid=c.contactid OR d.contactid=a.contactid
WHERE a.memberid=12345
This runs, and pulls the expected results. So far … I’m just wondering if there might be a better way.
Assuming that the fields you are joining on are indexed / or preferably defined with
FOREIGN KEYconstraints (which enforce indexing) you should be fine.However MySQL does not always use indexes even if they are available. To check the indexes are being used you can run an explain on your statement i.e.
the results will inform you which indexes are being used in the statement. If the results are not as expected you can force Mysql to use the indexes withby stating ‘force key for join
indexnameafter each reference to a table.