多列连接到单个列SQL Server 2008R2

时间:2015-09-01 07:17:54

标签: sql-server

我有2个彼此相关的表,Table1和Table2。

表1:

ID int IDENTITY Primary Key
Col1 varchar(15)

表2:

ID int IDENTITY Primary Key
CenterID int
SatelliteID int
Category varchar(15)

Table2.CenterIDTable2.SatelliteID引用Table1.ID(外键)。

问题是,我想检索标Table1Table2.CenterIDTable2.SatelliteID的{​​{1}}数据。

我应该如何加入引用相同密钥的2列?

这是我的代码

Table2.Category

3 个答案:

答案 0 :(得分:1)

您可以使用CenterID将Table2连接两次,使用SatelliteID连接第二次:

这样的事情应该有效:

SELECT t1.*, t2a.*, t2b.* FROM Table1
LEFT JOIN Table2 t2a ON t2a.CenterID = t1.id
LEFT JOIN Table2 t2b ON t2b.SateliteID = t1.id

答案 1 :(得分:1)

您可以执行以下操作:

select 
    table2.id,
    t1.Col1 as Center, 
    t2.Col1 as Satellite,
    table2.category
from table2 left join 
table1 t1 
on t1.ID= table2.centerid
left join table1 t2
on t1.ID= table2.satelliteid
--- add where criteria here

答案 2 :(得分:1)

你必须与表二进行多次连接

SELECT * 
FROM TableB AS b 
INNER JOIN TableA AS a1 ON b.CenterID  = a1.Id  
LEFT OUTER JOIN TableA AS a2 ON b.SatelliteID = a2.Id 

根据您的要求添加INNER JOIN或LEFT OUTER JOIN。