将多个查询联接到具有相同列名的表

时间:2019-12-18 17:56:57

标签: sql ms-access syntax

我有一个表“ tblEquipment”,其中包含:

Equipment
1000
1001
1002
1003
402
413
420
421
428
439
446
483
3000
3001
3002
3005

查询“ qry1”

Equipment   T1        T2           T3          T4
1000    2019-12-27                         2019-12-13
1001               2019-12-13       
1002                           2019-12-14   
1003    2019-12-25                         2019-12-06

第二个查询“ qry2”

Equipment     T1            T2           T3           T4
402                     2019-06-29      
413       2019-06-15    2019-12-12                2019-12-12    
420       2019-06-15    2019-12-12   2019-12-12 
421                     2019-09-01      
428                                  2019-09-01     
439       2019-07-30
446       2019-07-30
483                                             2019-06-29      

如何创建第三个查询以连接所有相关的T1,T2,T3,T4 tblEquipment中的每个设备?

以下代码是我一直试图使其正常运行的查询,但是我在FROM clase中不断收到语法错误。

SELECT e.Equipment, vehicule.T1, vehicule.T2, vehicule.T3, vehicule.T4
FROM tblEquipment e
JOIN qr1 vehicule
ON e.Equipment = vehicule.Equipment
UNION ALL
SELECT e.Equipment, cart.T1, cart.T2, cart.T3, cart.T4
FROM tblEquipment e
JOIN qr2 cart
ON e.Equipment = cart.Equipment;

2 个答案:

答案 0 :(得分:1)

MS Access不会自动将join语句识别为内部联接,您必须明确声明inner join

select e.equipment, vehicule.t1, vehicule.t2, vehicule.t3, vehicule.t4
from tblequipment e inner join qr1 vehicule on e.equipment = vehicule.equipment
union all
select e.equipment, cart.t1, cart.t2, cart.t3, cart.t4
from tblequipment e inner join qr2 cart on e.equipment = cart.equipment;

您也可以这样写:

select e.equipment, u.t1, u.t2, u.t3, u.t4
from
    tblequipment e inner join
    (
        select v.equipment, v.t1, v.t2, v.t3, v.t4 from qr1 v
        union all
        select c.equipment, c.t1, c.t2, c.t3, c.t4 from qr2 c
    ) u
    on e.equipment = u.equipment

答案 1 :(得分:0)

如果我正确地阅读了此内容,那么即使您第二次引用tblEquipment,也必须在第二个FROM语句的并集部分中使用,必须使用其他表引用名称,因此您希望它成为< / p>

UNION ALL
select f.equipment, cart.t1, cart.t2, cart.t3, cart.t4
from tblequipment f
join qr2 cart
on f.equipment = cart.equipment;