加入表示另一个表的两行之间的“传输”的表

时间:2015-09-14 17:45:32

标签: sql sql-server select join

对于令人困惑的标题感到抱歉;但是,描述和插图应该有希望清除它。

基本上,我有表A表示在表B.行之间传输“金额”的实例我想加入A B以便我可以显示转移的详细信息:

================= 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    |
+----+------+

我希望加入他们并制作一个“from name”栏和一个“to name”,如:

+-----+------+----+--------+
| 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 |
+-----+------+----+--------+

3 个答案:

答案 0 :(得分:4)

您可以a两次加入b

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 :(得分: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 

答案 2 :(得分: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;