使用网桥加入 table

Joining table using bridge

    Courses         Teachers        Students        StudentCourses
    CourseID        TeacherID       StudentID       CourseID
    CourseName      TeacherName     StudentName     StudentID
    TeacherID

您好,
这些是我的 table,我有两个问题..

  1. 我需要获取所有学生的名单以及每个学生注册了多少门课程
  2. 所有注册课程的学生都是从 "Art" 开始的。

我很困惑,因为 StudentCourses table。提前致谢!

1.

SELECT *
FROM Students s
INNER JOIN StudentCourses sc
ON  s.StudentID =  sc.StudentID
UNION
SELECT COUNT(courseID)
FROM StudentCourses dd
INNER JOIN Student ss
ON ss.studentID = dd.studentID
GROUP BY studentID

这种情况下是JOIN suitable吗?

2.

SELECT *
FROM Students s
JOIN StudentCourses sc
ON  s.StudentID =  sc.StudentID
JOIN Courses c
ON sc.COurseID = c.CourseID
WHERE CourseName = ‘Art%’

这是正确的吗?

对于您的第一个答案,您说您需要学生名单(我假设您的意思是您需要输出仅在学生 table 中可用的详细信息,例如姓名),以及有多少学生他们注册的课程。

这个问题的第二部分可以通过计算 studentcourses table 每个 studentid 有多少行来完成:

SELECT studentid, COUNT(courseID) num_of_enrolled_courses
FROM   studentcourses
GROUP BY studentID;

完成后,您可以简单地将此查询加入学生 table 以获取额外信息:

select s.studentname,
       sc.num_of_enrolled_courses
from   studentname s
       inner join (SELECT studentid, COUNT(courseID) num_of_enrolled_courses
                   FROM   studentcourses
                   GROUP BY studentID) sc on s.studentid = sc.studentid;

对于你的第二个查询,你几乎是正确的 - 你对课程 table 的过滤器需要是 CourseName like 'Art%'(即当你使用 like 而不是 '='进行通配符搜索)。您还需要只输出您感兴趣的列,可能是 students.studentname 和 courses.coursename.