2015-09-14 42 views
2

對不起,令人困惑的標題;然而,描述和插圖應該有希望將其清除。加入表格,表示另一個表格的兩行之間的「轉移」

從本質上講,我有我希望加入AB這樣我可以顯示轉移的細節表B.的行之間的轉移的「量」的表A代表實例:

================= A =================== 
+-----+-----------+----------+--------+ 
| AID | fromID(FK) | toID(FK) | amount | 
+-----+-----------+----------+--------+ 
| 1 |   1 |  5 | 100 | 
| 2 |   1 |  3 | 150 | 
| 3 |   5 |  3 | 500 | 
| 4 |   1 |  5 | 200 | 
| 5 |   4 |  5 | 800 | 
| 6 |   3 |  5 |  15 | 
+----+------------+----------+--------+ 

==== B ===== 
+----+------+ 
| BID | name | 
+----+------+ 
| 1 | a | 
| 2 | b | 
| 3 | c | 
| 4 | d | 
| 5 | e | 
+----+------+ 

我想加入他們生產出「從名稱」欄和「命名」,如:

+-----+------+----+--------+ 
| AID | from | to | amount | 
+-----+------+----+--------+ 
| 1 | a | e | 100 | 
| 2 | a | c | 150 | 
| 3 | e | c | 500 | 
| 4 | a | e | 200 | 
| 5 | d | e | 800 | 
| 6 | c | e |  15 | 
+-----+------+----+--------+ 

回答

4

您可以在b加入a兩次:

SELECT aid, from_b.name, to_b.name, amount 
FROM a 
JOIN b from_b ON from_b.bid = a.fromid 
JOIN b to_b ON to_b.bid = a.toid 
1

你可以用join做到這一點。

Fiddle with sample data

select aid, 
(select name from b where a.fromid = bid) as "from", 
(select name from b where a.toid = bid) as "to", 
amount 
from a 
+0

相關的子查詢ar e通常比連接慢。這是不好的技術。 – HLGEM

+0

@HLGEM其實,因爲優化器,從SQL 2005開始,這個查詢幾乎總是一樣的。 (有更復雜的情況下,它可能不會) – RBarryYoung

1

執行表之間的JOIN像下面,但你將不得不加入表B兩次

select a.AID, 
b.name as [from], 
b1.name as [to], 
a.amount 
from A a 
join B b on a.fromID(FK) = b.BID 
join B b1 on a.toID(FK) = B.bid; 
相關問題