困难的oracle查询

时间:2013-05-10 05:06:29

标签: sql oracle

我有一个如下所示的数据库:

table_Students: { studentid(PK), name };

table_Stu_cou:{ studentid(FK), courseid(FK) };

table_Courses:{ courseid(PK), coursename };

table_Tea_cou { courseid(FK), teacherid(FK) };

table_Teachers:{ teacherid(PK), name};

stu_cou表显示哪些学生参加哪些课程。 tea_cou表显示了哪些教师教授哪门课程。 我必须列出所有从未见过的学生和老师(学生从未上过这个讲师提供的课程)。但我无法弄清楚如何制作它并且我已经尝试了2天。你可以帮帮我吗?我正在使用Oracle。

3 个答案:

答案 0 :(得分:1)

SELECT s.name, t.name FROM students s CROSS JOIN teachers t
WHERE NOT EXISTS (
    SELECT 1 FROM courses c
    JOIN stu_cou sc ON sc.courseid = c.courseid AND sc.studentid = s.studentid
    JOIN tea_cou tc ON tc.courseic = c.courseic AND tc.teacherid = t.id
)

基本上,对于学生和老师的每一种可能的组合,是否有一个由该学生参加并由该老师教授的课程?

答案 1 :(得分:0)

你需要的是首先计算所有潜在的学生,教师,然后减去已经遇到的学生老师:

第一个是学生和老师的交叉产品。第二个基于课程的连接已经采取:

SELECT studentid, teacherid from students, teachers

EXCEPT

select studentid, teacherid from stu_cou natural join tea_cou;

如果您对学生姓名和教师姓名感兴趣,可以将此结果用作子查询,并加入学生和教师表格以获取该信息。但是我会把它留给你做练习。

- DMG

答案 2 :(得分:0)

一旦你修正了错别字

,这应该可以解决问题
select t.name, s.name
from  table_Teachers t, table_Students s
where not exists (
    select 'x' 
    from table_Stu_cou sc, table_Tea_cou tc
    where sc.courseid = tc.courseid
    and sc.studentid = s.studentid
    and tc.teacherid = t.teacherid
)