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).
这个查询不会给出我期望的输出。
最佳答案
尝试在下面使用通过别名连接 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
关于mysql - 连接两个不同列上的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52990811/