在左联接上显示AVG

时间:2019-03-02 13:22:32

标签: php mysql

我想在左侧联接中显示StudentQuizReading,StudentQuizLanguage和StudentQuizMath表的“分数”字段的平均值。

我该怎么做?

到目前为止,这是我的代码:

$query = "
SELECT s.StudentID
     , s.LastName
     , s.FirstName
     , s.MiddleName
     , s.Level
     , s.Adviser
     , r.Score
     , l.Score
     , m.Score 
  FROM Students s
  LEFT 
  JOIN StudentQuizReading r
    ON r.StudentID = s.StudentID
  LEFT 
  JOIN StudentQuizLanguage l
    ON l.StudentID = s.StudentID
  LEFT 
  JOIN StudentQuizMath m
    ON m.StudentID = s.StudentID
 WHERE s.StudentID = '".$_POST["StudentID"]."'
 ";

表格的详细信息:StudentQuizReading,StudentQuizLanguage,StudentQuizMath

+-----------+-------------+
| Field     | Type        | 
+-----------+-------------+
| StudentID | int(5)      |
| QuizNum   | varchar(10) | 
| Score     | int(2)      | 
+-----------+-------------+

1 个答案:

答案 0 :(得分:0)

您可以在null联接表列中检查StudentID中的LEFT,并可以找到平均值。

检查以下查询。

$query = "SELECT
  Students.StudentID,
  Students.LastName,
  Students.FirstName,
  Students.MiddleName,
  Students.Level,
  Students.Adviser,
  FirstQuarterGrades.Reading,
  FirstQuarterGrades.Language,
  FirstQuarterGrades.Mathematics,
  (SUM(IF(StudentQuizReading.StudentID IS NULL, 0, StudentQuizReading.Score)) / SUM(IF(StudentQuizReading.StudentID IS NULL, 0, 1))) AS StudentQuizReadingAvg,
  (SUM(IF(StudentQuizLanguage.StudentID IS NULL, 0, StudentQuizLanguage.Score)) / SUM(IF(StudentQuizLanguage.StudentID IS NULL, 0, 1))) AS StudentQuizLanguageAvg,
  (SUM(IF(StudentQuizMath.StudentID IS NULL, 0, StudentQuizMath.Score)) / SUM(IF(StudentQuizMath.StudentID IS NULL, 0, 1))) AS StudentQuizMathAvg
FROM Students
  LEFT JOIN StudentQuizReading ON Students.StudentID = StudentQuizReading.StudentID
  LEFT JOIN StudentQuizLanguage ON Students.StudentID = StudentQuizLanguage.StudentID
  LEFT JOIN StudentQuizMath ON Students.StudentID = StudentQuizMath.StudentID
WHERE Students.StudentID = '".$_POST["StudentID"]."'";