-2

我有老师和学生老师的桌子

id    teacherName    classAssigned
1          tea1                 1
2           tea2            1
3           tea3            3
4           tea4        2

学生桌有

id      name        class
1       st1              1
2       st2              1
3       st3              3
4       st4              4

我使用了左连接查询……。作为

SELECT  student1.name , teacher1.name
       FROM student1 LEFT JOIN teacher1 ON student1.class = teacher1.class where student1.class=1

Student_name         Teacher_name
St1         tea1
St1         tea2
St2         tea1
St2         tea2

现在我希望结果为

class       TeacherNo     Student_no
1             2                       2

因为 1 班有两个学生有两个老师 ..我得到的数是 4

4

2 回答 2

1

用于COUNT(DISTINCT )计算学生和教师,如下所示:

SELECT 
  student1.class,
  COUNT(DISTINCT student1.name)        AS studentno , 
  COUNT(DISTINCT teacher1.teacherName) AS Teacherno
FROM student1 
LEFT JOIN teacher1 ON student1.class = teacher1.classAssigned 
where student1.class = 1
GROUP BY student1.class;

在这里查看它的实际效果:

这会给你:

| CLASS | STUDENTNO | TEACHERNO |
---------------------------------
|     1 |         2 |         2 |
于 2013-05-23T09:39:41.617 回答
0

我的朋友尝试这个查询它会计算 class=1 的老师姓名和学生姓名

SELECT  class , Count(teacher1.name) as TeacherNo, Count(student1.name) as Student_no
       FROM student1 LEFT JOIN teacher1 ON student1.class = teacher1.classAssigned where student1.class=1
于 2013-05-23T09:44:37.500 回答