1

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

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

我想根据 Table.Number 有条件地仅加入表 2 或表 3 中的一个并保留别名,以便其他表仍将加入它们。

4

3 回答 3

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
于 2013-07-31T21:30:08.460 回答
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;
于 2013-07-31T21:15:24.323 回答
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,或者创建一个额外的表来保存关系。

于 2013-07-31T21:17:01.397 回答