MySQL视图 - 一行中的关系

时间:2014-10-27 20:37:08

标签: mysql

我有两张桌子:

表A

|| *handtool_id* || *1_wire_type_id* || *2_wire_type_id* || *3_wire_type_id* || *4_wire_type_id* || *5_wire_type_id* || *6_wire_type_id* ||
|| 1 || 5 || 7 || 9 || 1 || 1 || 1 ||
|| 2 || 1 || 1 || 1 || 1 || 1 || 1 ||
|| 3 || 1 || 1 || 1 || 1 || 1 || 1 ||
|| 4 || 4 || 5 || 7 || 1 || 1 || 1 ||

表B

|| *wire_type_id* || *wire_diameter* || *wire_type* ||
|| 1 || N/A || N/A ||
|| 2 || 0,5 || 5012050ZW ||
|| 3 || 0,75 || 5012075BL ||
|| 4 || 1,0 || 5012100ZW ||

我想创建一个带有表B中结果填充值的视图,但我在一行中重复使用了wire_type_id。

1 个答案:

答案 0 :(得分:1)

对于LEFT JOIN的每次迭代,您必须在TableB上执行X_wire_type_id

SELECT a.handtool_id, 
       b.wire_diameter,
       c.wire_diameter,
       d.wire_diameter,
       e.wire_diameter,
       f.wire_diameter,
       g.wire_diameter
FROM <tableA> a 
LEFT JOIN <tableB> b ON b.wire_type_id = a.1_wire_type_id
LEFT JOIN <tableB> c ON c.wire_type_id = a.2_wire_type_id
LEFT JOIN <tableB> d ON d.wire_type_id = a.3_wire_type_id
LEFT JOIN <tableB> e ON e.wire_type_id = a.4_wire_type_id
LEFT JOIN <tableB> f ON f.wire_type_id = a.5_wire_type_id
LEFT JOIN <tableB> g ON g.wire_type_id = a.6_wire_type_id