我两次获得相同的对象

时间:2016-12-29 21:35:04

标签: sql ms-access

我正在尝试获得包含某个学期的成绩的学生的所有课程。

橙色关系是相关关系: The orange relations are the relevant relations

查询:

SELECT 
tg.nhsColor AS cellColor,
tg.nhsTgradeName AS LessonName,
lsons.nhsLessonID AS LessonID,
lsons.nhsTgradeID AS TgradeID,
lsons.nhsDay AS nhsDay,
lsons.nhsHour AS nhsHour,
tg.nhsTeacherID AS TeacherID
FROM 
nhsTeacherGrades AS tg,
nhsLessons AS lsons,
nhsLearnGroups,
nhsMembers AS mem,
nhsGrades AS grd 
WHERE 
tg.nhsTgradeID = lsons.nhsTgradeID 
AND nhsLearnGroups.nhsTgradeID = tg.nhsTgradeID 
AND mem.nhsUserID = nhsLearnGroups.nhsStudentID
AND mem.nhsGradeID = grd.nhsGradeID 
AND grd.nhsGradeName LIKE '%"+gradePart+"%'

查询有效,但是我从这个查询中得到了两次相同的课程。

1 个答案:

答案 0 :(得分:1)

至少有两个原因可以获得重复:

  • 同样的课程可以在不同的教师成绩中发生,然后是某个学生
  • 不同的学生可以遵循相同的教师成绩

以下(未经测试的)嵌套SQL可以解决这个问题。它获得每节课的教师成绩ID,并检查其中哪一个至少有一个可行的学生与之相关联:

SELECT     tg.nhsColor AS cellColor,
           tg.nhsTgradeName AS LessonName,
           lsons.nhsLessonID AS LessonID,
           lsons.nhsTgradeID AS TgradeID,
           lsons.nhsDay AS nhsDay,
           lsons.nhsHour AS nhsHour,
           tg.nhsTeacherID AS TeacherID
FROM       nhsLessons AS lsons
INNER JOIN nhsTeacherGrades AS tg 
        ON tg.nhsTgradeID = lsons.nhsTgradeID
WHERE      tg.nhsTgradeID IN (
              SELECT     grp.nhsTgradeID
              FROM       (nhsLearnGroups grp
              INNER JOIN nhsMembers AS mem 
                      ON mem.nhsUserID = grp.nhsStudentID)
              INNER JOIN nhsGrades AS grd
                      ON mem.nhsGradeID = grd.nhsGradeID 
              WHERE      grd.nhsGradeName LIKE '%"+gradePart+"%' 
           ) 

请注意,我使用了JOIN语法,这被认为比在WHERE子句中放置连接条件更好。 MS Access在JOIN子句中使用括号非常讨厌,因此您可能需要使用它们来使其工作。