[英]Join 1 table to 2 tables on the same column
我有以下表格:
+------+-----------+----------+
| Item | ProcessID | PersonID |
+------+-----------+----------+
| 111 | 33 | 1234567 |
+------+----+------------+
| 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.