Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do LEFT OUTER JOIN but only return first row if matched?

The schema is pretty straightforward:

  • A Business has many Customers
  • A Customer may have zero to many Phones
  • A Customer may have zero to many Emails
  • Both Phone and Email tables have an ‘IsPrimary’ bool field to reflect the primary one to use

So I tried this but that WHERE clause will effectively eliminate the LEFT OUTER JOIN’s ability to return records where there are zero Phones or Emails. If I leave the WHERE out I get multiple Phone/Emails when I just want the IsPrimary one (if exists). How do I tackle this best? Thanks

    SELECT b.BusinessName, c.FirstName, c.LastName, p.PhoneNumber, e.EmailAddress,
    FROM Business b 
    INNER JOIN Business b ON c.BusinessId = b.BusinessId 
    LEFT OUTER JOIN Phone p ON p.CustomerId = c.CustomerId
    LEFT OUTER JOIN Email e ON e.CustomerId = c.CustomerId
    WHERE p.IsPrimary = true AND e.IsPrimary = true

PS: this is MySQL 5.6

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The condition should be moved to ON clause:

SELECT b.BusinessName, c.FirstName, c.LastName, p.PhoneNumber, e.EmailAddress,
FROM Business b 
INNER JOIN Business b ON c.BusinessId = b.BusinessId 
LEFT OUTER JOIN Phone p ON p.CustomerId = c.CustomerId AND p.IsPrimary = true
LEFT OUTER JOIN Email e ON e.CustomerId = c.CustomerId AND e.IsPrimary = true
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading