繁体   English   中英

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

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

我有以下表格:

表格1

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

表2

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

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

我想像这样加入他们

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

但是仅仅做一个简单的连接并不能使我到达那里。

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

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

由于要查找两个不同的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

我相信周星驰的解决方案也可能有效。

暂无
暂无

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

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