所以我正在学习MySQL,我正在努力做到以下几点:
每位教师列出他/她的名字和他/她指导的学生人数。
架构的相关部分是:
Person(ID, Name)
Student(StudentID, MentorID)
Instructor(InstructorID)
InstructorID
和StudentID
都映射到Person.ID
,而MentorID
映射到InstructorID
(每位学生都有一位导师导师,教师和学生都是人)。
我尝试过以下无效:
select p.Name, count(select s.StudentID
from Student s
where s.MentorID = i.InstructorID)
from Person p, Instructor i
where p.ID = i.InstructorID;
这也是在阅读了StackOverflow上的一些内容之后:
select InstructorDetails.Name, count(Mentees)
from Instructor i
inner join Person as InstructorDetails
on InstructorDetails.ID = i.InstructorID
inner join Student as Mentees
on Mentees.MentorID = i.InstructorID;
有什么建议吗?
答案 0 :(得分:4)
您的查询缺少GROUP BY
,
SELECT InstructorDetails.Name, count(*) totalCount
FROM Instructor i
INNER JOIN Person as InstructorDetails
ON InstructorDetails.ID = i.InstructorID
INNER JOIN Student as Mentees
ON Mentees.MentorID = i.InstructorID
GROUP BY InstructorDetails.Name