所以我有 3 个表,分别名为 menus
、products
和 categories
。
menus 表有 id,item_type 可以是 product|category 和 item_id。
我想做的是当 menu item_type = product
时,将其与产品表 ON products.id = menu.item_id
连接并与 当 item_type = category 时的类别
。
这是我当前的查询:
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'
虽然我没有看到每个菜单附加的任何产品或类别数据,但查询有效。
我是不是漏掉了什么?谢谢。
最佳答案
您需要SELECT
您想要的列。您只需从 menus
表中选择列,这就是您得到的全部内容。
我建议从其他两个表中选择列,但使用 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'
关于mysql - 如何根据主表的字段值连接到 2 个不同的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56746160/