简体   繁体   中英

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 . I want to eventually get the Owner_ID that are in table 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. 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

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
  • All rows that respect the condition Owner_ID = Owner_2

and you will return all of them at once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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