关联表而不扭曲数据

时间:2017-04-15 09:31:44

标签: mysql sql database join

我花了一整天时间试图让这个查询起作用,并且很想知道是否有人可以指出我哪里出错了。

这是我目前的查询:

SELECT   CONCAT(STUDENT.FirstName, ' ', 
         STUDENT.LastName) AS 'Student Name', 
         `UNIT`.UnitCode, SUM(STUDENT_ASSESSMENT.MarkAwarded) AS 'Sum of Marks Awarded'
FROM     `STUDENT_ASSESSMENT`
JOIN     `STUDENT` 
ON       `STUDENT_ASSESSMENT`.StudentID = `STUDENT`.StudentID
JOIN     `ASSESSMENT` 
ON       `STUDENT_ASSESSMENT`.AssessmentID = `ASSESSMENT`.AssessmentID
JOIN     `UNIT` 
ON       `ASSESSMENT`.Unitcode = `UNIT`.UnitCode
GROUP BY STUDENT.StudentID
ORDER BY `STUDENT`.LastName, `STUDENT`.FirstName, `UNIT`.UnitCode

它工作正常,做我想要的。

工作查询结果:

enter image description here

但是我正在尝试加入一个名为UNIT_ENROLMENT的表,它具有我需要访问的属性。当我尝试加入它时会破坏我的数据。

SELECT   CONCAT(STUDENT.FirstName, ' ', 
         STUDENT.LastName) AS 'Student Name', 
         `UNIT`.UnitCode, 
         SUM(STUDENT_ASSESSMENT.MarkAwarded) AS 'Sum of Marks Awarded', 
         `UNIT_ENROLMENT`.FinalGrade
FROM     `STUDENT_ASSESSMENT`
JOIN     `UNIT_ENROLMENT` 
ON       `STUDENT_ASSESSMENT`.StudentID = `UNIT_ENROLMENT`.StudentID
JOIN     `STUDENT` 
ON       `UNIT_ENROLMENT`.StudentID = `STUDENT`.StudentID
JOIN     `ASSESSMENT` 
ON       `STUDENT_ASSESSMENT`.AssessmentID = `ASSESSMENT`.AssessmentID
JOIN     `UNIT` 
ON       `ASSESSMENT`.Unitcode = `UNIT`.UnitCode
WHERE    `UNIT_ENROLMENT`.Year = '2017'
GROUP BY STUDENT.StudentID
ORDER BY `STUDENT`.LastName, `STUDENT`.FirstName, `UNIT_ENROLMENT`.Session, `UNIT`.UnitCode

结果失真:

enter image description here

如果需要任何其他信息,请发表评论。任何帮助都非常适合

1 个答案:

答案 0 :(得分:0)

根据您分享的内容,您可以尝试:

加入ASSESSMENT和UNIT后加入UNIT_ENROLMENT:

SELECT   CONCAT(STUDENT.FirstName, ' ', 
     STUDENT.LastName) AS 'Student Name', 
     `UNIT`.UnitCode, 
     SUM(STUDENT_ASSESSMENT.MarkAwarded) AS 'Sum of Marks Awarded', 
     `UNIT_ENROLMENT`.FinalGrade
FROM     `STUDENT_ASSESSMENT`
JOIN     `STUDENT` 
ON       `STUDENT_ASSESSMENT`.StudentID = `STUDENT`.StudentID
JOIN     `ASSESSMENT` 
ON       `STUDENT_ASSESSMENT`.AssessmentID = `ASSESSMENT`.AssessmentID
JOIN     `UNIT` 
ON       `ASSESSMENT`.Unitcode = `UNIT`.UnitCode
JOIN     `UNIT_ENROLMENT` 
ON       `STUDENT_ASSESSMENT`.StudentID = `UNIT_ENROLMENT`.StudentID
AND  `UNIT_ENROLMENT`.UnitCode = `ASSESSMENT`.Unitcode
WHERE    `UNIT_ENROLMENT`.Year = '2017'
GROUP BY STUDENT.StudentID
ORDER BY `STUDENT`.LastName, `STUDENT`.FirstName, `UNIT_ENROLMENT`.Session, `UNIT`.UnitCode