2016-11-09 26 views
1

我正面臨一個問題。我正在創建一個像Temp_district一樣的過程。基於一些條件我們必須更改加入表

在有像基於某些條件下,我們必須改變連接表的要求。

like if(year=2016) then 
select * from table1 a join table2 b on (a.id=b.id) join table3 c on (c.id=b.id) join table4 d on d.id=a.id 


if(year<>2016) then 
select * from table1 a join table2 b on (a.id=b.id) join table3 c on (c.id=b.id) join table5 e on d.id=a.id; 

查詢幾乎是相同的,並且過分大的查詢,在只有一個表得到改變,如果一年不2016這裏即表4至表5

有沒有像下面

if(year=2016) then 
with temp_table_2016 (select * from table4) 
else with temp_table_2016 (select * from table6) 
任何事情

這樣在單個查詢中,我可以用temp_table_2016替換table4或table5,根據條件它將從所需表中獲取數據。

+0

該解決方案將取決於你所使用的數據庫。 –

+0

你在四個不同的數據庫系統中面臨這個問題? – user272735

+0

我現在面臨的DB2 – Rams

回答

2

所以只是相對的條件加入兩個:

SELECT t.*, 
     COALESCE(t4.col,t5.col) as col, 
     COALESCE(t4.col2,t5.col2) as col2, 
     .... 
FROM t 
LEFT JOIN t4 ON(t.id = t4.id AND year = 2016) 
LEFT JOIN t5 ON(t.id = t5.id AND year <> 2016) 

你需要的所有表列添加COALESCE(),所以纔有了相應的數據就會出現。如果你不在意,你可以選擇他們兩個,其中1個將始終爲NULL

+0

謝謝你這麼多的問題...解決方案是工作的罰款......再次感謝各位 – Rams

+0

多了一個疑問,如果說不同的表是第一個表那麼什麼是它的解決方案... plz幫助。 – Rams

+1

@RameshYelda使用一個虛表的話..'SELECT * FROM(SELECT 1爲Dummy_Col)Dummy_Table LEFT JOIN Varying_Table_1 ON(年= 2016)... LEFT JOIN Varying_Table_2 ON(年<> 2016)...' – sagi

0

你可以用它實現這樣的,如果你使用的是MSSQL:

DECLARE @secondtable NVARCHAR(20) 

if(year=2016) 
BEGIN 
SET @secondtable = 'table4' 
END 

if(year<>2016) 
BEGIN 
SET @secondtable = 'table5' 
END 



EXEC('select * from table1 a join table2 b 
on (a.id=b.id) join table3 c on (c.id=b.id) join '[email protected]+' d on d.id=a.id')