我的问题是写一个SQL查询来返回所有教过课程的老师的名字,其中至少有2名学生在课程中获得B-
或更好。
我的表是:
Courses(id, name, teacher_id)
Grades(student_id, course_id, grade)
Students(id, name, email, password)
Teachers(id, name)
我使用了以下查询:
SELECT * FROM grades JOIN teachers WHERE grades.grade = 'B-'
但显示所有老师喜欢
答案 0 :(得分:2)
您可以使用exists()来检查每位教师是否存在超过2'b-'或更好的课程
所以你的查询应该是:
SELECT * FROM Teachers t
WHERE EXISTS(SELECT c.teacher_id from Courses c
inner join grades g ON c.id= g.course_id
where t.id = c.teacher_id and g.grade in('B-','B','A-','A','A+')
group by c.teacher_id having count(*) > 1)
答案 1 :(得分:0)
这应该有效:
Select distinct Teachers.name from Courses join Teachers on Courses.teacher_id = Teachers.id where Courses.id in (Select course_id from (Select course_id, count(student_id) as 'total' from Grades where grade = 'B-' or grade = 'B' or grade = 'B+' or grade = 'A-' or grade = 'A' group by course_id) a where a.total > 1)