[英]Join more than two tables on a same column
例如,如果我在MySQL数据库中有这三个表:
表1: wood_items (列:wood_item_id,item_name,宽度,高度,厚度,价格)
表2: other_items (列:other_items_id,item_name,价格)
表3: 交易 (列:transaction_id,item_id,价格)
我想将item_id上的wood_items和other_items表都加入事务表,因此无论它是wood_item还是other_item,它都会显示所有已完成的交易(要显示的列:transaction_id,item_name,price)。 它可能与Java中的继承有相似的概念,因为wood_items和other_items都应该是item 。
有可能做到吗? 如果是这样,如何; 但是,如果不能,创建相似结构/结果的最佳方法是什么?
如果可以的话,我将重组您的表,因为应该只有一个items
表,并且当然可以有另一个表来categories
“木材”。
失败的话,您可以使用LEFT JOIN
删除两个表上都存在匹配索引的要求。
SELECT cols FROM
transaction
LEFT JOIN wood_items ON (wood_item_id = item_id)
LEFT JOIN other_items ON (other_items_id = item_id)
WHERE
-- Ensures that there is a match in at least one of the tables
wood_item_id IS NOT NULL
OR other_items_id IS NOT NULL
您可以在JOIN之后在wood_items和other_items之间创建一个UNION,但是为此,您需要在wood和other之间设置固定数量的列,如果仅选择“ id”列,则类似的事情应该起作用(我已经添加了类型字段以区别它来自哪个表):
(SELECT T.transaction_id, T.item_id, T.price, W.item_name AS item_name, W.price AS item_price
FROM transaction T
LEFT JOIN wood_items W ON W.wood_items.wood_item_id = T.transaction.item_id)
UNION (SELECT T.transaction_id, T.item_id, T.price, , O.item_name AS item_name, O.price AS item_price
FROM transaction T
LEFT JOIN other_tiems O On O.other_items.other_items_id = T.transaction.item_id);
编辑:我已经添加了您需要的字段,它应该可以根据需要工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.