0

I have 2 tables:

  • courses: a list of open courses
  • student_courses: students who have signed up for a course

Tey are described below:

courses:
id
name
approved_by

student_courses:
id
student_id
course_id
paid

I want to list all courses with the following for each course: course id and the number of students signed up for that course. I've tried things like:

SELECT courses.id, SUM(student_courses.id)
FROM courses as courses
LEFT JOIN student_courses as student_courses on student_courses.course_id=courses.id
WHERE courses.approved_by != '0'

But that is only returning 1 row.

4
  • 1
    You have no GROUP BY clause, needed for the aggregate SUM(). Commented Jan 2, 2012 at 23:42
  • In your query, you are using a table 'students' that you didn't define in your schema description. You are also joining the students table onto an 'instructor_id' field, that both wasn't defined and doesn't make sense to join to students. Could you clarify this, as there seem to be other variables here that might throw off anyone trying to help you out. Commented Jan 2, 2012 at 23:47
  • Students first & last name was just a join, but I removed them for simplicity! Commented Jan 2, 2012 at 23:49
  • If course_id refers to a section of a course, then you probably do not need the "id" field on the "student_courses" table. In that case a composite key of "student_id" and "course_id" should be enough to ensure uniqueness. Commented Jan 2, 2012 at 23:55

1 Answer 1

3
SELECT courses.id
     , courses.name
     , COUNT(student_courses.id) AS number_of_students    ---COUNT(), not SUM()
FROM courses 
  LEFT JOIN student_courses  
    ON student_courses.course_id = courses.id
WHERE courses.approved_by <> '0'
GROUP BY courses.id

HAVING COUNT(student_courses.id) < courses.student_slots 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! One last question: How can I use number_of_students in my WHERE (for example, I want to only grab the courses that are not full). I tried modifying my where to be: WHERE courses.approved_by <> '0' AND number_of_students < courses.student_slots But I get: "Unknown column 'number_of_students' in 'where clause'"
See my edit. Such conditions (that involve values that are calculated during GROUP BY should be put in HAVING clause)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.