我有五个表学生,班级,科目,分数和分数。我在这些表上执行内部联接以返回结果。这是我的架构的样子:
学生表:
students
--------
id *
name
class_id (fk)
主题表:
subjects
--------
id *
name
班级表:
classes
--------
id *
name
条款表:
terms
--------
id *
name
得分表:
scores
---------------
id *
student_id (fk)
subject_id (fk)
class_id (fk)
term_id (fk)
score
现在这是我写的返回结果的查询:
SELECT students.name as Name, subjects.name as Subject, classes.name as Class, terms.name as Term, scores as Score
// id 1 for student Nathan
// term 1 for first Period
// term 2 for second period
// term 3 for third period
from scores
inner join students
on students.id = scores.student_id
and scores.student_id = 1
inner join subjects
on subjects.id = scores.subject_id
and scores.student_id = 1
inner join classes
on classes.id = scores.class_id
and scores.student_id = 1
inner join terms
on terms.id = scores.term_id
and scores.student_id = 1
where scores.term_id = 1 or scores.term_id = 2 or scores.term_id = 3
ORDER BY scores.term_id;
这是查询返回的结果:
毫无疑问,这会返回正确的结果,但我遇到的小问题是它没有按照我需要的方式进行格式化或结构化。 这有点说明我希望它如何成为结构:
PerioOne,PeriodTwo和PeriodThree分别对应于得分表中的术语ID及其得分。上面的图片显示了它将如何在html表格中显示的最终结果。
这就是我希望在mysql中返回结果的方法:
Name | subject | class | first Period | Second Period | Third Period
--------------------------------------------------------------------
Nathan | 1 | 1 | 96 | 71 | 74
Nathan | 2 | 1 | 96 | 71 | 74
有没有办法可以重构我的查询来完成这项工作?为清楚起见,这里是我的分数表中的数据: