[英]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.