Mysql – Join queries are not working as expected when trying to compare a count result with a value

join;MySQLquery

I'm learning SQL from a book and I'm trying to do some exercices on join queries. The only problem that I'm facing is that all of my join queries are not working while they seem well.

These are the tables:

    students(student_id,student_names,student_age)
    courses_students(course_id,student_id)
    courses(course_id,course_schedule,course_room,teacher_id)
    teachers(teacher_id,teacher_names)

The query is "which courses have more than 5 students enrolled?"

Here is what I've done:

select 
  course_name,
  count(select count(*) from courses) as count 
from students,courses,courses_students 
where students.student_id = courses_students.student_id,
courses.course_id = courses_students.course_id 
and count > 5

And the other one is "what are the names of students enrolled in at least 2 courses scheduled for the same hours?"

My query:

select student_name,schedule 
from students,courses,courses_students 
where students.student_id = courses_students.student_id,
courses.course_id = courses_students.course_id 
and count > 2

Best Answer

For the first question "which courses have more than 5 students enrolled?"

try the following query

select a.course_id,b.course_name,count(a.student_id) as student_count from courses_students a join courses b on a.course_id=b.course_id group by a.course_id having student_count>5;

For the second question "what are the names of students enrolled in at least 2 courses scheduled for the same hours"

try this

select a.student_id,a.student_name,b.course_schedule,count(b.course_id) as course_count from students a join courses b join courses_students c on b.course_id=c.course_id and a.student_id=b.student_id group by a.student_id,b.course_schedule having course_count>1;
Related Question