简体   繁体   English

我无法使用sql查询中的联接返回所有值,我在做什么错?

[英]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. 我需要一些指导,也许我的桌子安装不正确。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM