如何在Sql Server中查询多对多关系

时间:2016-04-19 14:43:30

标签: sql sql-server select

这是我的表enter image description here

我的问题是如何获取特定学生ID的课程名称

我尝试了这个,但没有工作

select Course.CourseName from Course
where Course.CourseId in (

select Student.studentname ,StudentCourse.CourseId from Student inner join StudentCourse
on Student.StudentId = StudentCourse.StudentId
  where Student.StudentId = 1)

你可以忘记我的查询,因为我是SQL Server的新手,只是告诉我开发人员在SQL Server真实世界中做了什么来获取特定学生的课程名称

3 个答案:

答案 0 :(得分:1)

正如你所说,你想知道这种方法,这只是基本观点

1)我们想看一下CourseName的。

SELECT CourseName FROM Course

2)一名学生可能有一门以上的课程。 3)因此,我们还有一个表是StudentCourse来实现这一目标。 4)我们必须在此表中查看CourseName的ID'S

SELECT CourseID FROM StudentCourse

5)找到哪些学生(X是你搜索的号码)参加这些课程。

WHERE StudentID = X

6)如果我们一起查看它们,我们现在通过步骤1获得所有CourseName。但我们不想要所有CourseName,并且我们拥有X编号学生所需的所有CourseID。因此,如果我们将它们组合在一起,现在我们将只选择X所需的CourseName。

WHERE CourseID IN

7)所以我们的最终结果是

SELECT CourseName FROM Course WHERE CourseID IN 
(SELECT CourseID FROM StudentCourse WHERE StudentID = X)

检查thisthis one,看看它是如何运作的。

答案 1 :(得分:0)

我正在使用左连接,以防你的学生没有分配任何课程,否则,如果你使用内部连接,你将得不到任何结果;

SELECT
s.StudentID
,s.StudentNam
,sc.CourseID
,c.CourseName
FROM Student s
LEFT JOIN StudentCourse sc
ON s.StudentID = sc.StudentID
LEFT JOIN Course c
ON sc.CourseID = c.CourseID
WHERE s.StudentID = 1

答案 2 :(得分:0)

试试这个:

select CourseName from Course
where CourseId in 
(select CourseId from StudentCourse
where StudentId = 1)
相关问题