请原谅我对这个问题的无知,如果它真的很简单,但它让我疯狂,我已经搜索过(尝试过和失败过)来自这个网站的不同解决方案,所以这里有...
我正在使用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
答案 0 :(得分: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
答案 1 :(得分: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.*, ...