简体   繁体   English

Oracle SQL plus 11g中的多表联接查询

[英]Multiple table joining query in Oracle SQL plus 11g

I have three tables. 我有三张桌子。

  1. table SCHOOL : schoolcode(PK), year, schoolname. SCHOOLSCHOOL代码(PK),年份,学校名称。
  2. table ENROLMENT : schoolcode, year, classname, enrol ENROLMENT :schoolcode,一年,类名,注册
  3. table CLASS : schoolcode, year, classid, rooms CLASS :学校代码,年份,classid,房间

Now, I want to find the list of schools with enrollment in classname - 1 to 4 and number of classrooms used by class 1-4. 现在,我想找到班级名称为1至4的学校和1-4级班级使用的教室数量的学校列表。

I used the following query: 我使用以下查询:

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 

but the result showing is not correct. 但是显示的结果不正确。 Enrollment is showing much higher than actual, same in case of classrooms. 入学率显示比实际要高得多,就教室而言。

Try this: 尝试这个:

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 

The way you have it: and e.classname in(1,2,3,4) is like having an OR operator in your where clause. 您拥有它的方式: 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)

So, c.classid can be "1" and e.classname can be "2" which is wrong 因此,c.classid可以为“ 1”,e.classname可以为“ 2”,这是错误的

UPDATE I still think the problem is that you don't connect the c.classid with e.classname 更新我仍然认为问题是您没有将c.classide.classname连接

Try it like this: 像这样尝试:

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 

try this: 尝试这个:

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM