JOIN查询以从另一个表中检索多个列引用到单个列

时间:2017-07-06 08:21:04

标签: sql-server join

下面是我的数据库图表,其中包含三个表及其关系 - PersonalInfoSubjectsStudents

Database diagram

目前,Students表的值低于此值。

Current data in Students table

我正在尝试查询要显示的数据如下。

Expected output

我尝试了什么

SELECT FullName, SubjectName AS 'Subject1', SubjectName AS 'Subject2',
SubjectName AS 'Subject3', SubjectName AS 'Subject4',SubjectName AS 'Subject5' 
FROM Subjects JOIN Students ON Students.Subject1 =Subjects.Id 
JOIN PersonalInfo ON PersonalInfo.Id=Students.StudId

获取低于输出的错误。它只显示第一个主题的名称。

Output

任何人都可以以正确的方式指导我。

2 个答案:

答案 0 :(得分:4)

您必须加入每个主题的多个时间。 “Sudent”和“PersonalInfo”表格ID和外键存在混淆。所以请根据设计加入。下面的查询将根据您的需要为您提供所有主题名称。请将查询视为逻辑。我可能会在此处输入语法错误

Select SUB1.SubejctName as Subject1,SUB2.SubejctName as Subject2,SUB3.SubejctName as Subject3,SUB4.SubejctName as Subject4,SUB5.SubejctName as Subject5, from Students S 
    inner join Subjects SUB1 on SUB1.id=S.Subject1
    inner join Subjects SUB2 on SUB2.id=S.Subject2
    inner join Subjects SUB3 on SUB3.Id=S.Subject3
    inner join Subjects SUB4 on SUB4.id=S.Subject4
    inner join Subjects SUB5 on SUB5.Id=S.Subject5

Todo - 加入PersonalInfo表以显示学生姓名。

答案 1 :(得分:1)

工作查询

SELECT FullName, 
sb.SubjectName AS 'Subject1', 
sb2.SubjectName AS 'Subject2',
sb3.SubjectName AS 'Subject3', 
sb4.SubjectName AS 'Subject4',
sb5.SubjectName AS 'Subject5' 
FROM Students s 
JOIN PersonalInfo ON PersonalInfo.Id=s.StudId
JOIN Subjects sb ON s.Subject1 =sb.Id 
JOIN Subjects sb2 ON s.Subject2 =sb2.Id 
JOIN Subjects sb3 ON s.Subject3 =sb3.Id 
JOIN Subjects sb4 ON s.Subject4 =sb4.Id
JOIN Subjects sb5 ON s.Subject5 =sb5.Id

<强>结果

https://www.w3schools.com/css/css_table.asp