2017-08-06 98 views
-1

嗨,大家好,我想在這裏加入表格,我想添加一個名爲Table2的表格,以便來自該表格的學生也顯示出來。令人困惑的是我已經加入了這個查詢,那麼應該如何添加另一個連接,以便同時顯示Table2中的學生,而不會破壞現有的代碼。此外,有沒有辦法,我可以檢查輸出PostgreSQL加入多個表

的ID varables在stTable 1 stsidno,sidno表2中,scsidno表schedprd

下面的代碼:

   String selS = "select distinct stdistrict,stschool,stsidno," 
        + " sname as name,stgrade," 
        + "S.recnum as recnum, S.stldate as stldate,scsec,sctea,sccor,scgrade,scclsprd,scgrdprd," 
        + "case when P.scchangestartdate is null then C.clstart else " 
        + "P.scchangestartdate end as scchangestartdate, " 
        + "case when S.stedate is null or S.stedate<C.clstart " 
        + "then C.clstart else S.stedate end as stedate " 
        + "from stTable1 as S join schedprd as P on " 
        + "(scyear=styear and scdistrict=stdistrict and scschool=stschool " 
        + "and stsidno=scsidno and (scsec is not null and scsec<>'')) " 
        + "left outer join calendar as C on (C.clyear=S.styear and " 
        + "C.cldistrict=S.stdistrict and C.clschool=S.stschool and C.cltype='10') " 
        + "where styear=? and stdistrict=? "; 
+0

表1和表2中的學生是不同的學生們?表1和表2的結構是否相同? –

+0

結構相同table1包含變量,如stdistrict,stschool,以st開頭的那些 –

+0

除非我們知道您的數據結構和表之間的關係,否則很難判斷哪些連接可能導致重複記錄。這導致無法重寫查詢以提高效率。 –

回答

0

你可以UNION表1和表2在一起Common Table Expression (CTE),然後在您的查詢中引用CTE而不是表1,如下所示:

WITH CTE 
AS 
(
SELECT * 
FROM Table1 
UNION 
SELECT * 
FROM Table2 
) 

select distinct 
stdistrict, 
stschool, 
stsidno, 
sname as name, 
stgrade, 
S.recnum as recnum, 
S.stldate as stldate, 
scsec, 
sctea, 
sccor, 
scgrade, 
scclsprd, 
scgrdprd, 
case when P.scchangestartdate is null then C.clstart else P.scchangestartdate end as scchangestartdate, 
case when S.stedate is null or S.stedate<C.clstart then C.clstart else S.stedate end as stedate 
from CTE as S 
join schedprd as P on (scyear=styear and scdistrict=stdistrict and scschool=stschool and stsidno=scsidno and (scsec is not null and scsec<>'')) 
left outer join calendar as C on (C.clyear=S.styear and C.cldistrict=S.stdistrict and C.clschool=S.stschool and C.cltype='10') 
where styear=? and stdistrict=?; 
+0

不會減慢執行速度嗎?作爲其已執行的選擇stdistrict,stschool,stsidno和其他東西從表1 –

+0

運行它,看看!擔心實際情況,而不是maybes –