2017-08-06 63 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 –