我有两张桌子:
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排。
答案 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