MYSQL得到的结果量

时间:2009-10-03 17:34:41

标签: sql mysql

当你使用mysql时,你可以这样做:

SELECT * FROM student WHERE teacher_id = 1

...然后你得到了结果的数量,并得到了结果。但是我只希望得到大量的结果,然后是每位老师。

这可能在像sizeof这样的mysql中吗?

另外,如果有老师没有学生,那么列表中没有吗?还是要说0?

3 个答案:

答案 0 :(得分:3)

你是说你想要每个老师的学生人数?你可以使用这样的东西:

SELECT teacher_id, count(*) AS student_count
FROM student
GROUP BY teacher_id

这不包括没有学生的教师。要将它们包含在结果中,您需要使用JOIN(假设您有一个teacher表):

SELECT teacher.id, sum(if(student.id IS NULL, 0, 1)) AS student_count
FROM teacher
    LEFT JOIN student ON student.teacher_id=teacher.id
GROUP BY teacher.id

答案 1 :(得分:1)

SELECT teacher_id, count(*) as count FROM student GROUP BY teacher_id;

答案 2 :(得分:1)

使用:

   SELECT t.teacher_id,
          IFNULL(ns.num_students, 0)
     FROM TEACHERS t
LEFT JOIN (SELECT s.teacher_id,
                  COUNT(s.student_id) 'num_students'
             FROM STUDENTS s
         GROUP BY s.teacher_id) ns ON ns.teacher_id = t.teacher_id