简体   繁体   中英

SQL command to perform division

I have the following tables.

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)

Find the names of all students who have taken every course taught by Einstein.

The sql command which I used is

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')
           );

Please explain where I am making a mistake or is there any other way to perform division in SQL?

I think outer join is needed here, something like

  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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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