简体   繁体   English

将1个表连接到同一列的2个表

[英]Join 1 table to 2 tables on the same column

I have the following tables: 我有以下表格:

Table1 表格1

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

Table2 表2

+------+----+------------+
| 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: 我认为这需要人员表的别名,因此可以在两个联接中使用它:personid和Representativepersonid:

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. 由于要查找两个不同的personid值,因此您必须两次加入“ Persons

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. 我相信周星驰的解决方案也可能有效。

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

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