Given a fake example where there are contacts and for each contact there can be one or zero Sms records; I can do this
SELECT Contact.id, Contact.name, Sms.provider, Sms.number FROM Contact, Sms WHERE Sms.contactId = Contact.id.
But I it needs to show a row even if there is no SMS number for that contact.
I know of two ways to accomplish this. One is with a UNION of two selects
(SELECT Contact.id, Contact.name, Sms.provider, Sms.number FROM Contact, Sms WHERE Sms.contactId = Contact.id) UNION (SELECT id, name, null provider, null number FROM Contact WHERE (SELECT 1 FROM Sms WHERE contactId = Contact.id) IS NULL).
and another is two substatements
SELECT id, name, (SELECT provider FROM Sms WHERE contactId = Contact.id) provider, (SELECT number FROM Sms WHERE contactId = Contact.id) number FROM Contact
The UNION method requires going through the database twice and the substatements method requires two lookups on the same table.
I run into this often and I prefer to have all the code in MySQL and not to work with the software code to accomplish this. Working with MySQL usually turns out to be more efficient as well as simpler. Many of the real situations I work with involve large databases.
Is there a way to get two fields from a related table with one query?
Then use a
LEFT OUTER JOIN, which returns a row from the left table even if there is no corresponding row in the right table.It’s a good idea to learn to always use JOIN syntax instead of the pseudo-inner-join when you just list tables with commas.