具有相同别名的SQL条件连接

时间:2013-07-31 21:08:59

标签: sql sql-server sql-server-2008

我在这样的查询中有一个join子句。

SELECT Table1.Number

FROM Table1

JOIN Table2 AS Table on Table2.Table1_ID = Table1.ID
JOIN Table3 AS Table on Table3.Table1_ID = Table1.ID

JOIN OtherTable on Table.ID = OtherTable.Table_ID

我想有条件地只连接表2或3中的一个,具体取决于Table.Number并保留别名,以便其他表仍然可以加入它们。

3 个答案:

答案 0 :(得分:1)

select T1.*, OT.*
from Table1 as T1
    inner join (
        select 1 as Number, T.Col, T.Table1_ID, T.Table_ID from Table2
        union all
        select 2 as Number, T.Col, T.Table1_ID, T.Table_ID from Table3
    ) as T2 on T2.Number = T1.Number and T2.Table1_ID = T1.ID
    inner join OtherTable as OT on OT.Table_ID = T2.Table_ID

或(可能效率较低)

select T1.*, OT.*
from Table1 as T1
    left outer join Table2 as TMP1 on TMP1.Table1_ID = T1.ID and T1.Number = 1
    left outer join Table3 as TMP2 on TMP2.Table1_ID = T1.ID and T1.Number = 2
    cross apply (select isnull(TMP1.Table_ID, TMP2.Table_ID) as Table_ID) as T2
    inner join OtherTable as OT on OT.Table_ID = T2.Table_ID

答案 1 :(得分:0)

仅当两个表具有相同的列(或至少是一个公共列子集)时才有效:

SELECT Table1.Number,Table.Id,OtherTable.Id
FROM Table1
CROSS APPLY(
  SELECT col1,col2,col3 FROM Table2
  WHERE Table2.Table1_Id = Table1.Id
  UNION ALL
  SELECT col1,col2,col3 FROM Table3
  WHERE Table3.Table1_Id = Table1.Id
) AS Table
JOIN OtherTable 
ON Table.ID = OtherTable.Table_ID;

答案 2 :(得分:0)

您可以通过将两个表合并为一个派生表来欺骗它。

SELECT Table1.Number
FROM Table1 t1
INNER JOIN 
  (SELECT ID, Table1_ID FROM TABLE2
  UNION ALL
  SELECT ID, Table1_ID FROM TABLE3) t ON t.Table1_ID = t1.ID
JOIN OtherTable o ON t.ID = o.Table_ID

但我认为这里的表结构是错误的。

o.Table_ID能够指向两个不同的表将无法通过约束强制实施参照完整性。此外,两个表中可能同时存在ID。

根据引用(很难用这些假名称猜测),我会在OtherTable中创建两个不同的列,在Table2和Table3中创建一个FK到OtherTable,或者创建一个额外的表来保存关系。