用于执行除法的SQL命令

时间:2015-10-08 05:52:58

标签: sql database relational-database sqlcommand relational-division

我有以下表格。

STUDENT(ID, FIRST_NAME, LAST_NAME, MAJOR)
INSTRUCTOR(ID, FIRST_NAME, LAST_NAME, DEPARTMENT, SALARY)
COURSE(ID, COURSE_NAME, DESCRIPTION)
COURSE_OFFERING(ID, COURSE_ID, INSTRUCTOR_ID,  SEMESTER)
GRADE(STUDENT_ID, COURSE_OFFERING_ID,  GRADE)

找出所有学过爱因斯坦所教课程的学生的姓名。

我使用的sql命令是

select STUDENT_ID 
from grade where not exists
   (select grade.COURSE_OFFERING_ID from grade 
    where grade.COURSE_OFFERING_ID not in 
           (
             select course_offering.ID 
             from instructor join course_offering 
             where instructor.ID = course_offering.INSTRUCTOR_ID 
             and instructor.FIRST_NAME = 'Einstein')
           );

请解释我在哪里犯了错误,或者有没有其他方法在SQL中执行除法?

1 个答案:

答案 0 :(得分:0)

我认为这里需要外连接,比如

  select STUDENT_ID, count(*) cnt
  from grade 
  left join course_offering c on COURSE_OFFERING_ID = c.ID
  left join instructor i on INSTRUCTOR_ID = i.ID and i.LAST_NAME='Einstein'
  where c.ID is NULL
  group by STUDENT_ID
  having cnt=0;