Mysql JOIN / SUM查询

时间:2012-01-02 23:39:58

标签: mysql

我有两张桌子:

  • 课程:开放课程列表
  • student_courses:已注册课程的学生

Tey如下所述:

courses:
id
name
approved_by

student_courses:
id
student_id
course_id
paid

我想列出所有课程,每门课程包括以下内容:课程编号和注册该课程的学生人数。我尝试过这样的事情:

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'

但那只返回1排。

1 个答案:

答案 0 :(得分: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