The code below is completely wrong and does not work at all. Im basically trying to look through my tables and compile a list of DeptName and the total student number for a department where a department has more than 40 students.
Im confused about joins in general and if someone could explain and show where im going wrong. im sure there is also other problems so any help with them would help
So basically one department is connected to one module, and a student is enrolled in a module. A student cannot take a module outside of their department. So each student should have one module that connects to one department
All of the ID fields in other tables are foreign keys as you can guess and changing the tables is not what I want to do here I just want to do this query as this stands
Relevant tables columns
Table Department DeptID
, DeptName
, Faculty
, Address
Table Modules ModuleID
, ModuleName
, DeptID
, Programme
Table Students StudentID
,StudentName
,DoB
,Address
,StudyType
,`
Table Enrolments EID
,StudentID
,ModuleID
,Semester
,Year
SELECT Department.DeptName, COUNT(Student.StudentID) AS 'No of Students' FROM Department LEFT JOIN Module ON Department.DeptID= Module.DeptID LEFT JOIN Enrolment ON Module.ModuleID= Enrolment.StudentID LEFT JOIN Student.StudentID
GROUP BY(Department.DeptID)
HAVING COUNT(Student.StudentID)>=40
I have not included every table here as there are quite a lot.
But unless i’ve got this completely wrong you don’t need to access a ModuleID in a staff table for the module they teach or something not relevant to this at all. As no student or Dept details are in there.
If that is the case i will fix it very quickly.
3
Answers
Instead of
left join
you need to useinner join
since you need to select related rows only from those three tables.Groupy by
andhaving
clause seems fine. Since you need departments with more than 40 students instead of>=
please useCOUNT(e.StudentID)>40
So your join clause was a bit iffy to
students
as you wrote it, and presumably these should all be inner joins.I’ve reformatted your query using aliases to make it easier to read.
Since you’re counting the number of rows per DeptName you can simply do
count(*)
, likewise in yourhaving
you are after counts greater than 40 only. Without seeing your schemas and data it’s not possible to know if you might have duplicate Students, if that’s the case and you want distinct students count can amend tocount(distinct s.studentId)
Also, looking at your join conditions, is the Enrolement table relevant?
USING
instead ofON
for joinsJOIN
operator has to be a table, not a column.COUNT
. I recommend that you select the DeptID instead of the name, then use the result of this query to look up the name in a subsequent select.Note : Following code is untested.