I am writing a web page that displays students grades in an old grade book format which is to say, it displays the Student name, then their score for each assignment (in a row) then repeats one row per student. My tables are set up as follows (shortened to necessary info):
Table: Assignment
* Assignment_PK (Primary Key) * Assignment_NameTable: Student
* Student_PK (Primary Key)
Table: StudentAssignment
* SA_PK (Primary Key * Student_FK (Student.Student_PK) * Assignment_FK (Assignment.Assignment_PK) * ScoreI am trying to write a SELECT statement that will print the students name and score for each assignment. The problem I'm running into is that if I SELECT Score as a column, I only get the score for one assignment because in my WHERE Assignment_FK = Assignment_PK only allows me to pick one Score for a column.
I'm fairly new to Relational Databases and I could really use some help on the best way to tackle this. One suggestion was that I write a SELECT statement to pick all Students into a tab开发者_开发知识库le, then do a foreach row in the table and have it select the scores and place them in the appropriate column. This seems like a slow and unnecessary process. Is there any easier way using JOINS? Or writing a better SELECT?
This should get you the data you need. You can then investigate pivoting it into the desired display format, which may be easier in your application than in the database.
SELECT s.Student_Name, a.Assignment_Name, sa.Score
FROM Student s
INNER JOIN StudentAssignment sa
ON s.Student_PK = sa.Student_FK
INNER JOIN Assignment a
ON sa.Assignment_FK = a.Assignment_PK
ORDER BY s.Student_Name, a.Assignment_Name
精彩评论