PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

[FIXED] How to use two left joins in one query

 October 28, 2022     left-join, mysql     No comments   

Issue


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:

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;


Answered By - Marco
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing