简体   繁体   English

Mysql 联合/加入多列帮助

[英]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.下面是两个表的示例,每个表都有大约 20 列不同的数据。

Table 1表格1

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

Table 2表 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.我要做的是显示所有表 1,但使用匹配的 item_id 将 containerID、productID 和 packageID 替换为表 2 中的名称。 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.尝试在使用 foreach 的 mysql 之外执行此操作,但表 2 有 30k 行,当尝试显示表 1 中的数百行并将每个 id 替换为其等效名称时,它“只是有点”滞后。

To see all the table_1 records, use:要查看所有 table_1 记录,请使用:

   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.您可以将它们更改为 INNER JOIN,但与所有三个不匹配的任何行都不会出现在结果集中。

My query uses table aliases, because you have to join to the appropriate TABLE_2 column for each name you want to look up.我的查询使用表别名,因为您必须为要查找的每个name加入相应的TABLE_2列。

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您需要为每个 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确保 table_2 的 itemid 上有索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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