简体   繁体   English

在两个不同的列上联接表

[英]join tables on two different columns

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

I have two table I want to join with eachother. 我有两个桌子想要互相连接。 It is only possible to join on the Owner_ID = Owner_1 or Owner_ID = Owner_2 . 只能以Owner_ID = Owner_1Owner_ID = Owner_2 I want to eventually get the Owner_ID that are in table 1 aswel. 我想最终得到的Owner_ID是在表1 aswel。

My expected results: 我的预期结果:

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 

As you see if the Owner_ID does not appear in table 1 I don't want it to appear in the joint table, but when joining 7894 as there is a relationship in table 2 it will apear anyway the way I am joining them. 如您所见,如果Owner_ID没有出现在表1中,我不希望它出现在联合表中,但是当加入7894时,因为表2中存在关系,无论如何我都会以这种方式出现。 I need help with the joining of these two 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). 

This query wont give the output I expect. 该查询不会提供我期望的输出。

Try below using join with multiple instance of table2 by alias 尝试通过别名对table2的多个实例使用join

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 

You can try somehting like this : 您可以尝试这样的操作:

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

This way you will get : 这样,您将获得:

  • All rows that respect the condition Owner_ID = Owner_1 所有符合条件的行Owner_ID = Owner_1
  • All rows that respect the condition Owner_ID = Owner_2 所有符合条件的行Owner_ID = Owner_2

and you will return all of them at once. 您将立即全部退还。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM