如何从多个表中选择记录

时间:2013-02-25 17:15:18

标签: tsql

如果有人能告诉我如何从12张桌子中选择一条记录,我会很高兴。

主要问题是我为每个科目设置了一个表格,用于存储学生获得的分数。

每个主题表包含以下列:StudentId,RegId,AcademicYear,Term,Form,ClassScore,ExamScore,Total,Grade。

包含学生人口统计记录的studentDetails.Students表格以StudentId列为主键。

2 个答案:

答案 0 :(得分:1)

使用联合查询的示例:

SELECT au_lname FROM authors
UNION ALL
SELECT lname FROM Employee
ORDER BY au_lname

答案 1 :(得分:1)

您可以通过几种不同的方式返回数据。

您可以在JOIN表和所有students表之间使用subjects

select *  -- replace this with the columns you want to return
from Students s
left join subject1 s1
    on s.studentid = s1.studentid
left join subject2 s2
    on s.studentid = s2.studentid
left join subject3 s3
    on s.studentid = s3.studentid
left join subject4 s4
    on s.studentid = s4.studentid;

请参阅SQL Fiddle with demo

或者您可以使用以下类似的内容将students表与在每个UNION ALL表之间使用subject的子查询连接起来:

select s.StudentId, S.StudentName, S.Photo,
   sb.StudentId, sb.RegId, sb.AcademicYear, 
   sb.Term, sb.Form, sb.ClassScore, sb.ExamScore, sb.Total, sb.Grade
from students s
inner join
(
    select s1.StudentId, s1.RegId, s1.AcademicYear, 
          s1.Term, s1.Form, s1.ClassScore, s1.ExamScore, s1.Total, s1.Grade, 
          'Subject1' as src
    from subject1 s1
    union all
    select s2.StudentId, s2.RegId, s2.AcademicYear, 
          s2.Term, s2.Form, s2.ClassScore, s2.ExamScore, s2.Total, s2.Grade, 
          'Subject2' as src
    from subject2 s2
    union all
    select s3.StudentId, s3.RegId, s3.AcademicYear, 
          s3.Term, s3.Form, s3.ClassScore, s3.ExamScore, s3.Total, s3.Grade, 
          'Subject3' as src
    from subject3 s3
) sb
    on s.studentid = sb.studentid

请参阅SQL Fiddle with Demo

如果您想要加入另一个表,那么您将使用:

select s.StudentId, S.StudentName, S.Photo,
   sb.StudentId, sb.RegId, sb.AcademicYear, 
   sb.Term, sb.Form, sb.ClassScore, sb.ExamScore, sb.Total, sb.Grade,
   r.programofstudy
from students s
inner join
(
    select s1.StudentId, s1.RegId, s1.AcademicYear, 
          s1.Term, s1.Form, s1.ClassScore, s1.ExamScore, s1.Total, s1.Grade, 
          'Subject1' as src
    from subject1 s1
    union all
    select s2.StudentId, s2.RegId, s2.AcademicYear, 
          s2.Term, s2.Form, s2.ClassScore, s2.ExamScore, s2.Total, s2.Grade, 
          'Subject2' as src
    from subject2 s2
    union all
    select s3.StudentId, s3.RegId, s3.AcademicYear, 
          s3.Term, s3.Form, s3.ClassScore, s3.ExamScore, s3.Total, s3.Grade, 
          'Subject3' as src
    from subject3 s3
) sb
    on s.studentid = sb.studentid
left join Registration r
    on s.studentid = r.studentid 
    and sb.regid = r.regid