Madhatter5501
Madhatter5501

Reputation: 163

I am unable to return all values using joins in my sql query, what am I doing wrong?

I have three tables - Assignment, Grades, Student and I am trying to make this query work so that it returns all assignments even if there is no grade entered for a student yet.

The tables are setup like this

Assignment

AssignmentId, AssignmentName, PointsPossible

Grades (Junction table)

StudentId, AssignmentId, PointsReceived

Student

 StudentId, StudentName

My query:

select 
   s.StudentName, a.AssignmentName, g.PointsReceived, a.PointsPossible
from 
   student s 
cross join
   assignment a 
left outer join
   grades g on s.StudentId = g.StudentId and g.AssignmentId = a.AssignmentId
order by 
   s.StudentName;

When I run the query I get all the names I need, but I don't get all the assignments back. I should be getting all the names, all the assignments, and if the assignment hasn't been graded yet, there should be a null value returned.

I need a little direction, maybe my tables are setup incorrectly.

Upvotes: 0

Views: 61

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270061

You need to get all assignments even if there isn't a grade? The obvious question is: without a junction table, how do you know which assignments to provide for each student?

So, let me guess that you want to get a cross product of all students and all assignments, along with grades (if any). If so, you want to structure your query like this:

select s.StudentName, a.AssignmentName, a.PointsPossible, g.PointsReceived
from students s cross join
     assignments a left outer join
     grades g
     on g.StudentId = a.StudentId and g.AssignmentId = a.AssignmentId;
order by s.StudentName;

Upvotes: 1

Related Questions