Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join to 2 different tables based on field value of main table?

Tags:

sql

join

mysql

So I have 3 tables named menus, products and categories.

menus table has id, item_type which can be product|category and item_id.

What I'd like to do is when menu item_type = product, join it with the products table ON products.id = menu.item_id and join with categories when item_type = category.

This is my current query:

SELECT m.* FROM menus m 
LEFT JOIN products p ON p.id = m.item_id AND m.item_type = 'product' 
LEFT JOIN categories c ON c.id = m.item_id AND m.item_type = 'category'

The query works though I'm not seeing any product or category data attached to each menu.

Am I missing something here? Thanks.

like image 316
wobsoriano Avatar asked Oct 19 '25 03:10

wobsoriano


2 Answers

You need to SELECT the columns that you want. You are only selecting columns from the menus table, so that is all you get.

I would suggest selecting columns from the other two tables, but combining them using COALESCE():

SELECT m.*,
       COALESCE(p.name, c.name) as name,  -- or whatever the columns are
       -- repeat for additional columns that you want
FROM menus m LEFT JOIN
     products p
     ON p.id = m.item_id AND m.item_type = 'product' LEFT JOIN
     categories c
     ON c.id = m.item_id AND m.item_type = 'category'
like image 74
Gordon Linoff Avatar answered Oct 21 '25 17:10

Gordon Linoff


You are selecting only the values in menu by using a SELECT m.*

The correct query is to just use * or the fields you require specifically.

SELECT * FROM menus m 
LEFT JOIN products p ON p.id = m.item_id AND m.item_type = 'product' 
LEFT JOIN categories c ON c.id = m.item_id AND m.item_type = 'category'
like image 25
Jerome Avatar answered Oct 21 '25 18:10

Jerome



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!