2

请原谅我对这个问题的无知,如果它真的很简单,但它让我发疯,我已经从这个网站搜索(尝试和失败)不同的解决方案,所以这里......

我正在使用 SQL 2008 并尝试将结果从 12 个表中提取到一个查询中,所以我有;

DECLARE @RefID nvarchar(10)
SET @RefID = 'test'

SELECT * From 
Table1, 
Table2, 
Table3, 
Table4, 
Table5, 
Table6, 
Table7,
Table8,
Table9,
Table10,
Table11,
Table12

WHERE table1.[RefID] = @RefID
AND Table2.[Ref ID] = @RefID
AND Table3.[Ref ID] = @RefID
AND Table4.[Ref ID] = @RefID 
AND Table5.[Ref ID] = @RefID
AND Table6.[Ref ID] = @RefID 
AND Table7.[Ref ID] = @RefID 
AND Table8.[Ref ID] = @RefID 
AND Table9.[Ref ID] = @RefID 
AND Table10.[Ref ID] = @RefID 
AND Table11.[RefID] = @RefID 
AND Table12.[RefID] = @RefID `

现在这工作正常,易于理解,并给我一行将所有数据正是我正在寻找的......除了一个问题

如果任何表中都不存在记录,而不是忽略它或简单地给我该表的空白/空值 - 查询中断并且我没有得到任何结果

我真的很感激任何想法

TIA

4

2 回答 2

2

以下应该也可以工作......

select * 
from (select RefID = @RefID) x
left join Table1 t1 on t1.RefID = x.RefID
left join Table2 t2 on t2.RefID = x.RefID
left join Table3 t3 on t3.RefID = x.RefID
left join Table4 t4 on t4.RefID = x.RefID
left join Table5 t5 on t5.RefID = x.RefID
left join Table6 t6 on t6.RefID = x.RefID
left join Table7 t7 on t7.RefID = x.RefID
left join Table8 t8 on t8.RefID = x.RefID
left join Table9 t9 on t9.RefID = x.RefID
left join Table10 t10 on t10.RefID = x.RefID
left join Table11 t11 on t11.RefID = x.RefID
left join Table12 t12 on t12.RefID = x.RefID
于 2012-11-17T00:06:43.637 回答
0

意识到前两个想法是不对的:

Select
  *
From (
  Select 
    @RefID RefID
  ) a
    Left Outer Join
  Table1
    On a.RefID = Table1.RefID
  Table2 
    On a.RefID = Table2.RefID
    Left Outer Join
  Table3
    On a.RefID = Table3.RefID
    Left Outer Join
  Table4
    ...
    Left Outer Join
  Table12
    On a.RefID = Table12.RefID

如果您不想在开始时使用额外的 RefID,请替换*Table1.*, Table2.*, ...

于 2012-11-16T23:44:58.127 回答