将两个表的查询与另一个表联接

时间:2018-11-30 13:44:24

标签: database ms-access ms-access-2010

我需要帮助来连接三个表。我可以以某种方式联接两个表table1table2以获得所需的输出,但是我想联接 另一个表以获取一些新的相关列。 这是我的查询:

select 
[from_bus] as [Node], 
[from_bus_id]  as [Node_id]
from table1 
union 
select 
[to_bus] as [Node], 
[to_bus_id]  as [Node_id]
from table1
union
select 
[from_bus] as [Node], 
[from_bus_id]  as [Node_id]
from table2
union 
select 
[to_bus] as [Node], 
[to_bus_id]  as [Node_id]
from table2

查询表1和表2的输出:

Node Node_ID
A_22  1
A_11  2
B_33  3
C_25  4

Node和Node_ID是唯一的。 现在,我有了另一个table3,我需要从中另一个列(Zone_ref)包含相应的IDs的{​​{1}}。

Zone

我想要类似的东西

    table3: 
    Zone   Node_Name  Zone_ref
    A      A_22        1
    A      A_11        1
    B      B_33        3 
    B      B_44        3     
    C      C_31        4
    C      C_25        4

有一些公共字段可以连接表,但不知道如何将两个表中的一个查询与第三个表集成在一起。需要您的建议。顺便说一句,我正在使用访问数据库。谢谢。

1 个答案:

答案 0 :(得分:0)

尝试使用Join嵌套子查询。如下所示:

select a.Node, a.Node_id, b.Zone_ref from (
 select 
 [from_bus] as [Node], 
 [from_bus_id]  as [Node_id]
 from table1 
 union 
 select 
 [to_bus] as [Node], 
 [to_bus_id]  as [Node_id]
 from table1
 union
 select 
 [from_bus] as [Node], 
 [from_bus_id]  as [Node_id]
 from table2
 union 
 select 
 [to_bus] as [Node], 
 [to_bus_id]  as [Node_id]
 from table2 ) a
INNER JOIN table3 b ON a.Node = b.Node_Name