在sql中双重连接

时间:2018-02-05 14:15:45

标签: sql sql-server

我想从名为:connector

的表中选择3列
SELECT Start_ID, END_ID, ConnectionType FROM connector;
+----------+--------+----------------
| Start_ID | End_ID | ConnectionType|
+----------+--------+----------------
|    1     |   3    |  Association  |
|    3     |   4    |  Association  |
|    3     |   5    |  Association  |
|    5     |   7    |  Association  |
|    2     |   3    |  Composition  |
|    4     |   2    |  Association  |
|    5     |   1    |  Composition  |
|    7     |   1    |  Association  |
|    6     |   3    |  Association  |
|    6     |   2    |  Association  |

START和END ID是一个名为"对象表",

的表中的object_ID
+-----------+-------------+
| Object_ID | ObjectName  |
+-----------+-------------+
|    1      | Airplane    |
|    2      | car         |
|    3      | train       |
|    4      | bus         |
|    5      | motorcycle  |
|    6      | bycycle     |
|    7      | electric car|
+-----------+-------------+

所以我想在查询中显示系统名称而不是ID。系统名称仅存储在对象表中。

+------------+------------+---------------- 
| ObjectName | ObjectName | ConnectionType|
+------------+------------+----------------
|   Airplane |    train   |  Association  |
|     "      |     "      |  Association  |
|     "      |     "      |  Association  |
|     "      |     "      |  Association  |
|     "      |     "      |  Composition  |   
|     "      |     "      |  Association  |
|     "      |     "      |  Composition  |
|     "      |     "      |  Association  |
|     "      |     "      |  Association  |
|     "      |     "      |  Association  |
+------------+------------+---------------- 

1 个答案:

答案 0 :(得分:1)

LEFT JOIN表进行两次OBJECT

SELECT O1.ObjectName, O2.ObjectName, C.ConnectionType 
FROM Connector C
LEFT JOIN
    Object O1 ON O1.Object_ID = C.Start_Id
LEFT JOIN
    Object O2 ON O2.Object_ID = C.End_Id