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 use two left joins in one query

this is my menu table:

userID
date
lunch
dinner

and this is my food table:

id 
food_name

I save id of food in lunch and dinner of menu table
I want to get lunch name and dinner name from food_name table.
I can get one of columns name by using LEFT JOIN like this:

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

SELECT m.user_id,
       m.date,
       m.lunch,
       m.dinner,
       f.id,
       f.food_name
FROM 
       menu m 
LEFT JOIN foods f ON
       m.lunch = f.id;

But the above code just loads lunch name. What should I do to get lunch and dinner name in the same query?
Thanks

>Solution :

You could try:

SELECT m.user_id,
       m.date,
       m.lunch,
       m.dinner,
       f.id AS lunch_id,
       f.food_name AS lunch_name,
       g.id AS dinner_id,
       g.food_name AS dinner_name
FROM 
       menu m 
LEFT JOIN foods f ON
       m.lunch = f.id
LEFT JOIN foods g ON
       m.dinner = g.id;
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