简体   繁体   中英

Join more than two tables on a same column

For example if I have these three tables in a MySQL database:

Table 1: wood_items (columns: wood_item_id, item_name, width, height, thickness, price)

Table 2: other_items (columns: other_items_id, item_name, price)

Table 3: transaction (columns: transaction_id, item_id, price)

I want to join the transaction table with both of wood_items and other_items table on item_id, so it will display all transaction made (columns to display: transaction_id, item_name, price) regardless whether it's a wood_item or an other_item. It's probably share a similar concept to inheritance in Java, since both of wood_items and other_items are supposed to be an item .

Is it possible to do it? If so, how; but if I can't, what is the best way to create a similar structure/result?

I would restructure your tables if you can since there should be only one items table, and you can of course have another table for categories like "wood."

Failing that, you can use a LEFT JOIN to remove the requirement that a matching index exist on both tables.

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

You can make a UNION between wood_items and other_items after the JOIN but for this you need to have a fixed number of columns between wood and other, something like this should work if you select only the 'id' column (I have added a type field to make a difference between which table it comes from):

(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);

Edit: I have added the fields you need, it should work as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM