0

如果有人能告诉我如何从 12 个表中选择记录,我会很高兴。

主要问题是我为每个科目都有一个表格来存储学生获得的分数。

每个科目表都有以下列:StudentId、RegId、AcademicYear、Term、Form、ClassScore、ExamScore、Total、Grade。

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

4

2 回答 2

1

使用联合查询的示例:

SELECT au_lname FROM authors
UNION ALL
SELECT lname FROM Employee
ORDER BY au_lname
于 2013-02-25T17:20:39.117 回答
1

有几种不同的方法可以返回数据。

您可以在表和所有表JOIN之间使用 a :studentssubjects

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

或者您可以使用类似下面的方法将表与在每个表之间students使用 a 的子查询连接起来:UNION ALLsubject

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

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

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
于 2013-02-25T17:25:40.733 回答