Table 1 Bus_ID Owner_ID #owners in Bus
12345 5558 3
12345 5856 3
52858 **7894** 1
12345 1254 3
Table 2 Owner_1 Owner_2 Relationship
5558 5856 Parent of Owner_1
5558 1254 Parent of Owner_1
1254 5856 Spouse
5856 1254 Spouse
**7894** 6868 Spouse
6868 **7894** Spouse
我有两个要互相连接的桌子。只能加入Owner_ID = Owner_1
或Owner_ID = Owner_2
上。我最终希望获得表1中的Owner_ID
。
我的预期结果:
Bus_ID Owner_ID Owner_1 Owner_2 Relationship
12345 5558 5558 5856 Parent of Owner_1
12345 5558 5558 1254 Parent of Owner_1
12345 5856 5856 1254 Spouse
12345 1254 1254 5856 Spouse
您看到Owner_ID是否未出现在表1中,我不希望它出现在联合表中,但是当加入 7894 时,因为表2中存在关系,它将出现无论如何,我正在加入他们。在连接这两个表时,我需要帮助。
select Bus_ID, Owner_ID, Owner_1, Owner_2, Relationship from table 1
join table 2 on (Owner_ID = Owner_1 AND Owner_ID = Owner_2).
此查询不会提供我期望的输出。
答案 0 :(得分:0)
尝试通过别名将table2的多个实例与连接一起使用
select Bus_ID, Owner_ID, t2.Owner_1, t3.Owner_2, t2.Relationship
from table1 t1 join table2 t2 on t1.Owner_ID = t2.Owner_1
join table2 t3 on t1.Owner_ID = t3.Owner_2
答案 1 :(得分:0)
您可以尝试以下操作:
select
Bus_ID, Owner_ID, Owner_1, Owner_2, Relationship
from table 1
inner join table 2 on Owner_ID = Owner_1
UNION
select
Bus_ID, Owner_ID, Owner_1, Owner_2, Relationship
from table 1
inner join table 2 on Owner_ID = Owner_2
这样您将获得:
Owner_ID = Owner_1
的行Owner_ID = Owner_2
的行,您将一次返回所有这些。