I have a university practical next week on databases. I need to create 15 queries around a scheme on a university, which looks as follows:
- Student(Student_No, First_Name , Last_Name, Sex, Date-Of-Birth, Address, Level, Degree_Code)
- Degree(Degree_Code, Degree_Name, School_Name)
- Module(Module_Code, Module_Title, School_Name)
- School(School_Name, Faculty, Head-of-School)
- Take_Exam(Student_No, Module_Code, Mark)
I have completed 14 of the queries but I am stuck on this one:
- Retrieve the names of students who take every Module. (Hint. use not exists).
I have been reading up on not exists queries, but I just don’t even know where to start!
I created this piece of code:
select students.student_no, fname, lname, count(module_code)
from students left join take_exam using (student_no)
group by student_no
having count(module_code) < 19
order by lname;
This returns all students who DON’T take all 19 modules. However, I hate the code as it involves having < 19, which meant if the amount of modules ever changed later, this value would need changes which is inefficient.
Can anyone point me in the right direction and give me some guidance on using ‘not exists’ queries?
Thanks, Andrew
Using
not exists:Explanation :
For each student
sin the tableStudent, we’ll addsto the result, iff :not exists any module in table
Modulesuch that this module is not mapped to studentsin tableTake_Exam.It’s not intuitive, but it’s exactly the same as :
“all the students who take every module”