如何基于输入上的两个单独字段和连接表上的一个字段加入表?

时间:2014-04-08 00:02:39

标签: sql

我有两张桌子:

Contacts:
+----+----+
|Name| #  |
+----+----+
|Joe | 123|
+----+----+
|Jane| 456|
+----+----+

Calls:
+----+----+
|To  |From|
+----+----+
|123 | 456|
+----+----+
|456 | 123|
+----+----+

我需要创建一个返回如下表的查询:

Log:
+------+------+------+------+
|To    |ToName|From  |FrName|
+------+------+------+------+
|123   | Joe  |  456 | Jane |
+------+------+------+------+
|456   | Jane |  123 | Joe  |
+------+------+------+------+

这在概念上似乎很简单,但我根本无法弄清楚如何将SQL拼凑在一起。我已经尝试了嵌套的SELECTS和嵌套的JOINS,但是无法让它正确运行(如果有的话)。提前谢谢。

2 个答案:

答案 0 :(得分:2)

您基本上需要将呼叫加入两个联系人副本:

SELECT ca.To,
       co1.Name AS ToName,
       ca.From,
       co2.Name AS FrName
FROM Contacts co1 INNER JOIN Calls ca
ON co1.[#] = ca.To INNER JOIN Contacts co2
ON co2.[#] = ca.From

答案 1 :(得分:0)

我会这样做like this (SQL Fiddle)

SELECT c.to AS "To",
       t.name AS "ToName",
       c.from AS "From",
       f.name AS "FromName"
  FROM Calls c
  JOIN Contact AS t ON t.number = c.to
  JOIN Contact AS f ON f.number = c.from
 ORDER BY 1
;