连接两个不同列上的表

c6ubokkw  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(472)
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

我有两张table要一起坐。只能加入 Owner_ID = Owner_1 或者 Owner_ID = Owner_2 . 我想最终得到 Owner_ID 也在表1中。
我的预期结果:

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

如您所见,如果所有者id没有出现在表1中,我不希望它出现在联合表中,但是当加入7894时,因为表2中有一个关系,它将以我加入它们的方式出现。我需要帮助把这两张table连接起来。

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).

这个查询不会给出我期望的结果。

fruv7luv

fruv7luv1#

你可以试试这样的方法:

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 你会立刻把它们都还给我。

gcuhipw9

gcuhipw92#

请尝试在下面使用join with multiple instance of table2 by alias

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

相关问题