简体   繁体   中英

Mysql union/join help with multiple columns

At first I thought this may work as a join but I'm not sure if this is really a union command or if even possible. Below is an example of the two tables and each has about 20 more columns of various different data.

Table 1

>     id    assembly    user1    user2    containerID    productID    packageID
      1     line2       Billy    John     3794           4892         4589
      2     line4       John     Doug     7794           6201         7864

Table 2

>     item_id    name    width    height    weight    flag1    flag2
      3794       Box     10       10        10        0        1
      4892       Lamp    4        6         2         1        1
      7864       BigBox  200      200       300       4        5      

What I am trying to do is show all of Table 1 but replace the containerID, productID, and packageID with their name from Table 2 using the matching item_id. Tried doing this outside of mysql with foreach but with Table 2 having 30k rows it lags up "just a bit" when trying to display the hundreds of rows from Table 1 and replacing each id with its name equivalent.

To see all the table_1 records, use:

   SELECT t1.id, t1.assembly, t1.user1, t1.user2, 
          t2c.name, t2pr.name, t2pk.name
     FROM TABLE_1 t1
LEFT JOIN TABLE_2 t2c ON t2c.item_id = t1.containerid
LEFT JOIN TABLE_2 t2pr ON t2pr.item_id = t1.productid
LEFT JOIN TABLE_2 t2pk ON t2pk.item_id = t1.packageid

You can change those to INNER JOINs, but any row that doesn't match all three will not be in the resultset.

My query uses table aliases, because you have to join to the appropriate TABLE_2 column for each name you want to look up.

try to use something like this:

  SELECT id, assembly, user1, user2, 
         (SELECT name from table2 where item_id = table1.containerID), 
         (SELECT name from table2 where item_id = table1.productID), 
         (SELECT name from table2 where item_id = table1.packageID)
    FROM table1 
ORDER BY id;

You'll need to join each row three times for each item_id

   SELECT t1.*, t21.name,t22.name,t23.name FROM table_1 t1
       INNER JOIN table_2 t21 ON t1.containerID = t21.itemid
       INNER JOIN table_2 t22 ON t1.productId = t22.itemid
       INNER JOIN table_2 t23 ON t1.packageID = t23.itemid

Make sure there's an index on table_2's itemid

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