选择命令返回重复行

时间:2017-09-25 12:41:04

标签: sql sql-server sql-server-2008 c#-4.0 sql-server-2005

我有3张桌子:

表1 ExamTB

 ID   ExamTerm   ExamDate
 1    MidTerm    2017-09-24
 2    FinalTerm  2017-12-01

表2 ExamSubMarksTB

 ID  ExamID   ClassID  SubjectID TotalMarks  PassMarks
 1     1         1        1       100          50
 2     1         1        2       100          50
 3     1         1        3       100          50
 4     2         1        1       100          50
 5     2         1        2       100          50
 6     2         1        3       100          50

表3 ExamResultTB

ID   ExamID    ClassID    SubjectID  MarksObtain StdID
 1     1           1         1         80         1  
 2     1           1         2         70         1  
 3     1           1         3         60         1
 4     2           1         1         50         1  
 5     2           1         2         72         1  
 6     2           1         3         68         1 

现在,当我创建一个存储过程时,SELECT此选择命令会返回重复的行

SELECT ExamResultTB.ExamID
     , ExamTB.ExamTerm
     , ExamTB.ExamDate
     , ExamResultTB.StdID
     , StudentTB.Name
     , StudentTB.FatherName
     , ClassTB.ClassName
     , SubjectTB.Subject
     , ExamResultTB.ObtainMarks
     , ExamSubMarksTB.TotalMarks
     , ExamSubMarksTB.PassMarks
FROM ExamResultTB
     INNER JOIN ExamTB ON ExamResultTB.ExamID = ExamTB.ID
     INNER JOIN ClassTB ON ExamResultTB.ClassID = ClassTB.ID
     INNER JOIN SubjectTB ON ExamResultTB.SubjectID = SubjectTB.ID
     INNER JOIN StudentTB ON ExamResultTB.StdID = StudentTB.ID
     INNER JOIN ExamSubMarksTB ON ExamResultTB.ExamID = ExamSubMarksTB.ExamID
WHERE ExamResultTB.ExamID = 4
     AND ExamResultTB.StdID=1 

1 个答案:

答案 0 :(得分:1)

确定此行会产生重复的行:

INNER JOIN ExamSubMarksTB ON ExamResultTB.ExamID = ExamSubMarksTB.ExamID

你应该这样做:

INNER JOIN ExamSubMarksTB ON ExamResultTB.ExamID = ExamSubMarksTB.ExamID and 
ExamResultTB.ClassId = ExamSubMarksTB.ClassId and ExamResultTB.SubjectID = 
ExamSubMarksTB.SubjectID