2014-02-12 73 views
0

有沒有辦法讓if語句確定聯接是否有必要?如果內聯合聲明

我需要這個,因爲我查詢的數據中有多個外鍵。如果任何外鍵都爲空,我需要更改SQL語句。我想寫一個可以知道任何空值的語句。

這是我想怎麼辦...

select a.*,b.* from table1 a inner join table2 b on a.id = b.id 
if a.InspectorID is not null 
{inner join table3 c on a.InspectionID = c.id} 
else do nothing... 
+4

你能不能用一個'左連接'?還是我錯過了這一點? – christiandev

+1

不能使用動態SQL來更改查詢的*形狀*(所用表格,列數,結果集中列的名稱和類型)。但是在這種情況下,有什麼意義 - 你從不使用'c'中的任何列嗎? –

+0

我想我沒有完全理解左邊的加入...... christiandev謝謝 –

回答

1

嘗試了這一點...

select a.*,b.* from table1 a inner join table2 b on a.id = b.id 
left join table3 c on a.InspectionID = c.id 
where a.InspectorID is null or a.InspectionID = c.id 
1

我不知道,如果你可以有條件地加入表,但「如果」語句的T-SQL是卡列斯 case

1

怎麼樣使用union

select a.*,b.* 
from table1 a 
inner join table2 b on a.id = b.id 
inner join table3 c on a.InspectionID = c.id 
union all 
select a.*,b.* 
from table1 a 
inner join table2 b on a.id = b.id 
where a.InspectionID is null 
1

如果我理解正確的話,你可以使用:

select a.*,b.*,c.fields 
from table1 a inner join table2 b on a.id = b.id 
left join table3 c on a.InspectionID = c.id 
where a.InspectionID IS NOT NULL