从不同的表中选择count

vi4fp9gy  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(389)

假设我有两个相关的表: teacher 以及 Course 这意味着一个老师可以教很多课程,但一门课程一次只能有一个老师,所以我创建了两个表,如下所示:

create table teacher (
   id INT NOT NULL UNIQUE,
   name VARCHAR(50) NOT NULL,
   lastname VARCHAR(50) NOT NULL
);

create table Course (
   id INT NOT NULL UNIQUE,
   name VARCHAR(50) NOT NULL,
   teacher_id INT NOT NULL
);

例如,我得到的是这样的东西

| id | name     | lastname  | 
-----------------------------
| 1  | teacher1 | lastname1 |
| 2  | teacher2 | lastname2 |

| id | name     | teacher_id |
------------------------------
| 1  | course1  | 1          |
| 2  | course2  | 1          |
| 3  | course4  | 2          |

到目前为止,一切正常,但根据要求,我需要返回一份教师名单和多少课程,如:

| id | name     | lastname   | courses  |
----------------------------------------
| 1  | teacher1 | lastname1  |  2       |
| 2  | teacher2 | lastname2  |  1       |

我找不到任何能适应这一要求的解决办法。我试过了 HAVING 以及 GROUP BY 来自mysql的子句,但这似乎不像我需要的那样有效。

irtuqstp

irtuqstp1#

这应该可以做到:

select t.id, t.name, t.lastname, count(t.id) as courses
from course c
join teacher t on t.id = c.teacher_id
group by t.id
aemubtdh

aemubtdh2#

可以使用左联接,将教师表用作左表。它将从教师表中选择所有教师,您可以检索他们的课程id。如果教师没有课程,它仍然返回教师记录,但课程id为空。从那里您可以对课程id进行不同的计数。请参阅下面的:

select a.id,
a.name,
a.lastname,
count(distinct b.id) as courses
from teacher a
left join courses b on a.id=b.teacher_id
group by a.id,
a.name,
a.last_name;

下面是一幅说明不同类型联接的图像https://www.google.fr/amp/s/amp.reddit.com/r/programming/comments/1xlqeu/sql_joins_explained_xpost_rsql/

hts6caw3

hts6caw33#

GROUP BY 应该可以正常工作:

SELECT
    t.id,
    t.name,
    t.lastname,
    COUNT(DISTINCT course.id) AS courses
FROM teacher AS t
LEFT OUTER JOIN Courses AS c
    ON c.teacher_id = t.id
GROUP BY
    t.id,
    t.name,
    t.lastname

相关问题