寻找只教一门课的老师

时间:2017-02-28 05:54:59

标签: mysql sql

我想问一下,我将在查询中添加哪些内容来选择仅教授一个课程的内容。我的表是:

Teacher                         Course
ID    Name                      Course_ID   Teacher_ID
1     George                    1           1
2     Sam                       2           2
3     Julie                     3           1

我想获得只教一门课程的老师ID。我有:

select teacher.id
from teacher, course
where teacher.id = course.teacher_id;

我在考虑添加

having (count(course.teacher_id)) = 1

where count(t) = (select count(*) from course) and t = 0

但是我得到了"无效使用群组错误"。如何更改它以修复我的查询?

3 个答案:

答案 0 :(得分:1)

请尝试以下代码。希望这会有所帮助。

select teacher.id
from teacher, course
where teacher.id = course.teacher_id
GROUP BY course.teacher_id
HAVING COUNT(course. Course_ID) =1

答案 1 :(得分:1)

您尝试的内容几乎就在那里,只需添加group by,然后使用join而不是,来组合表格:

select teacher.id
from teacher
join course
on teacher.id = course.teacher_id
group by teacher.id
having (count(course.Course_ID)) = 1 -- note count(Course_ID), not count(teacher_id)

答案 2 :(得分:0)

加入小组并拥有:

select *
from teacher
where id in (
    select teacher_id
    from course
    group by teacher_id
    having count(*) = 1)