简体   繁体   中英

Join 1 table to 2 tables on the same column

I have the following tables:

Table1

+------+-----------+----------+
| Item | ProcessID | PersonID |
+------+-----------+----------+
| 111  |    33     |  1234567 |

Table2

+------+----+------------+
| Item | ID | DelegateID |
+------+----+------------+
| 111  | 1  |  4567894   |

Persons

+----------+------+
| PersonID | Name |
+----------+------+
| 1234567  | Jhon |
+----------+------+
| 4567894  | Larry|

and I want to join them like this

+-----------+--------+----------+
| ProcessID | Person | Delegate |
+-----------+--------+----------+
|    33     |  Jhon  |  Larry   |

But doing just a simple join doesn't get me there.

SELECT Table1.processid, Persons.name,  
 (select name from Persons where personid =Table2.delegatepersonid) as delegate
FROM Persons 
INNER JOIN Table1 ON Persons.personid = Table1.personid
INNER JOINTable2 ON Table1.item= Table2.item

I think this calls for an alias of the persons table so it can be used in two joins: personid and delegatepersonid:

select P.*, T1.*, T2.*
from persons P
inner join table_1 T1 on P.personid = T1.personid 
inner join table_2 T2 on T1.item = T2.item
inner join persons P_del on T2.delegatepersonid = P_del.personid ;

You will have to join to Persons twice since you are looking for two different personid values.

SELECT 
        one.processid
    ,   pone.name
    ,   ptwo.name
FROM table1 AS one 
INNER JOIN table2 AS two 
    ON one.item = two.item
INNER JOIN persons as pone
    ON pone.personid = one.personid
INNER JOIN persons as ptwo 
    ON ptwo.personid = two.delegatepersonid

I believe Tracy Zhou's solution may work as well.

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