Oracle SQL加11g中的多表连接查询

时间:2012-08-06 12:12:33

标签: sql oracle

我有三张桌子。

  1. SCHOOL:学校代码(PK),年份,学校名称。
  2. ENROLMENT:学号,年份,班级名称,注册
  3. CLASS:schoolcode,year,classid,rooms
  4. 现在,我想找到一个名为1到4的学校名单和1-4班级使用的教室数量。

    我使用了以下查询:

    select 
        m.schoolcode, m.schoolname, sum(e.c1+e.c2+e.c3+e.c4), sum(c.rooms) 
    from 
        dise2k_enrolment09 e, dise2k_master m, dise2k_clsbycondition 
    where 
        m.schoolcode = e.schoolcode 
        and m.schoolcode = c.schoolcode 
        and e.year = '2011-12' and m.year = '2011-12' and c.year = '2011-12' 
        and classid in (1,2,3,4) 
        and e.classname in (1,2,3,4) 
    group by 
        m.schoolcode, m.schoolname 
    

    但结果显示不正确。入学率远高于实际入学率,同样适用于教室。

2 个答案:

答案 0 :(得分:1)

试试这个:

select m.schoolcode, m.schoolname, sum(e.c1+e.c2+e.c3+e.c4), sum(c.rooms) 
from dise2k_enrolment09 e, dise2k_master m ,dise2k_clsbycondition c
where m.schoolcode=e.schoolcode and m.schoolcode=c.schoolcode and e.year='2011-12' and m.year='2011-12' and c.year='2011-12' 
and c.classid in(1,2,3,4) 
and e.classname = c.classid
group by m.schoolcode, m.schoolname 

你拥有它的方式:and e.classname in(1,2,3,4)就像在你的where子句中有一个OR运算符。

(c.classid=1 or c.classid=2 or c.classid=3 or c.classid=4) 
and 
(e.classname=1 or e.classname=2 or e.classname=3 or e.classname=4)

所以,c.classid可以是“1”而e.classname可以是“2”,这是错误的

更新我仍然认为问题在于您未将c.classide.classname

相关联

试试这样:

select m.schoolcode, m.schoolname, sum(e.c1+e.c2+e.c3+e.c4), sum(c.rooms) 
from dise2k_enrolment09 e, dise2k_master m ,dise2k_clsbycondition c
where m.schoolcode=e.schoolcode and m.schoolcode=c.schoolcode and e.year='2011-12' and m.year='2011-12' and c.year='2011-12' 
and c.classid in(1,2,3,4) 
and c.classid = decode(e.classname,1,7,2,7,3,8,4,8,5,9,6,9,7,10,8,10)
group by m.schoolcode, m.schoolname 

答案 1 :(得分:0)

试试这个:

 select m.schoolcode, m.schoolname, sum(e.c1+e.c2+e.c3+e.c4), sum(c.rooms) 
from dise2k_enrolment09 e join dise2k_master m
on  m.schoolcode=e.schoolcode 
join dise2k_clsbycondition c
on m.schoolcode=c.schoolcode
where  e.year='2011-12' and m.year='2011-12' and c.year='2011-12' 
and classid in(1,2,3,4) 
and e.classname in(1,2,3,4) 
group by m.schoolcode, m.schoolname