在同一列上加入两个以上的表

时间:2013-11-26 17:21:29

标签: mysql sql

例如,如果我在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 表加入交易表,因此它会显示所有已完成的交易(列显示:transaction_id,item_name,price)无论是wood_item还是other_item。它可能与Java中的继承有相似的概念,因为 wood_items other_items 都应该是项目

有可能吗?如果是这样,怎么样;但如果我不能,创建类似结构/结果的最佳方法是什么?

2 个答案:

答案 0 :(得分:3)

如果可以,我会重组您的表格,因为只有一个items表格,您当然可以为categories添加另一个表格,如“wood”。

如果失败,您可以使用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

答案 1 :(得分:0)

你可以在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);

编辑:我添加了您需要的字段,它应该可以正常工作。