Here is the schema:
Student(Snum, Sname)
Course(Cnum, Cname)
Prerequisite(Cnum, Prereq)
Professor(Pnum,Pname, Dept, Office)
Enrollment(Snum, Cnum, Term, Section, Mark)
Schedule(Cnum, Term, Section, Days, Time, Room)
Class(Cnum, Term, Section, Instructor)
The full question is:
Find professors (Pnum, Pname, Dept) who whenever taught a course in the Class relation, either the course does not have any prerequisite or the professor has also taught each of the prerequisites of the course. A professor taught a course exactly when the professor taught a class (a section of a course) in some term.
My starting point so far...
SELECT * FROM Class c
LEFT JOIN Prerequisite p ON p.Cnum = c.Cnum
WHERE p.Cnum IS NULL
I know how to find the courses that the professors taught that have no prerequisites, and therefore they satisfy part of the condition. The next step is finding if they have taught the prerequisites if there are any. Also, my current query only selects a single prerequisite for every class, when there can really be multiple prerequisites for a class.
Note: Cnum and Prereq are both foreign keys to Cnum
Thanks for any help! This is a toughie.
EDIT: I came up with the final answer!
SELECT prof.Pnum, prof.Pname, prof.Dept FROM Professor prof
WHERE prof.Pnum NOT IN
(
SELECT DISTINCT c.Instructor FROM Class c
RIGHT JOIN Prerequisite p ON p.Cnum = c.Cnum
LEFT JOIN Class cpre ON cpre.Cnum = p.Prereq AND cpre.Instructor = c.Instructor
WHERE cpre.Instructor IS NULL AND c.Instructor IS NOT NULL
)