【发布时间】:2017-04-24 14:04:26
【问题描述】:
我有五 (5) 个表:students、subjects、period_one、period_two 和 period_three。我正在执行左连接以从这五个表中选择值:
学生桌(学生)
student_id | Name
--------------|-------
1 |John
2 |Peter
3 |Flomo
科目表(科目)
subject_id |SubjectName
-----------------|-------
math101 |Mathematics
eng201 |English
lang303 |Language Arts
一期表(period_one)
id|student_id |subject_id| score
--------------|----------|-----
1 |1 | math101 |99
2 |2 | eng201 |88
3 |3 | lang303 |77
周期二表(period_two)
id|student_id |subject_id| score
--------------|----------|-----
1 |1 | math101 |100
2 |2 | eng201 |60
3 |3 | lang303 |65
周期三表(period_three)
id|student_id |subject_id| score
--------------|----------|-----
1 |1 | math101 |71
2 |2 | eng201 |51
3 |3 | lang303 |71
这是我用来检索记录的查询Query1:
SELECT period_one.student_id, period_one.subject_id, period_one.score, period_two.score,period_three.score
from period_one
LEFT JOIN period_two
ON period_one.subject_id = period_two.subject_id
AND period_one.student_id = period_two.student_id
LEFT JOIN period_three
on period_one.subject_id = period_three.subject_id
AND period_one.student_id = period_three.student_id
WHERE period_one.student_id = 10
上面代码的问题是,如果我要查找的学生 id 不在第一个表中(periodOne),则左连接应用于查询返回 null,即使该学生的记录在其他表中表(周期二和周期三)。我查找了问题 (https://www.w3schools.com/sql/sql_join_left.asp) 并确认这不是最好的处理方式。
然后我做了一些更改
因此,我将查询更新为如下所示(Query2):
SELECT students.student_id, period_one.score, period_one.subject_id,
period_two.score, period_two.subject_id, period_three.score,
period_three.subject_id
from students
LEFT JOIN period_one
ON students.student_id = period_one.student_id
LEFT JOIN period_two
ON students.student_id = period_two.student_id
LEFT JOIN period_three
ON students.student_id = period_three.student_id
WHERE students.student_id = 3 或 period_one.student_id = 3 或 period_two.student_id = 3 或 period_three.student_id = 3
这很完美,因为学生表是所有周期表引用的主表。这样,如果学生 ID 不在 period_one 和 period_two 表中而是在 period_there 中,则返回该表的 studentId、subjectId 和 score。
然后又出现了一个问题
在我更新我的代码之前,我以我想要的方式显示记录,但没有以期望的方式获取/检索记录。这就是促使我更改查询的原因,因为我注意到这是问题所在。
现在,根据我的第一个查询 (Query1),我从 select 语句中的各个表中选择了 subject_id。当我显示记录时,我将查询返回的 subject_id 传递到获取该 ID 的主题名称的函数中。这就是我显示结果的方式:
如果学生 ID 在分配给 from 子句的表中,则此方法有效,否则不返回任何内容。这就是我更改代码的原因。
但现在我将代码更改为 (Query2) 我无法显示主题 ID 及其名称,因为它不在学生表中。以下是关于我如何显示我的记录的要点:https://gist.github.com/nathansiafa/e9d22791800d4ba3a00e2b98de52baec
有什么方法可以让它更好地工作吗?将感谢建议和反馈。谢谢!
【问题讨论】:
-
如果您可以发布创建表查询,它会更容易提供帮助。
-
students.current_class_id = period_one.class_id既不是students也不是period_one表有这些列。你能提供当前表格的结构吗? -
另外,如果您可以包含一些示例数据,那也会很有帮助。
-
@Stefano Zanini 对不起。你们是对的。但我尽我所能删除一些现在不需要的东西。在我的主要项目中, students.current_class_id = period_one.class_id 在那里,但我觉得这里没有必要,因为它对我想要完成的事情没有太大影响。请看一下我已经做了一些更新的代码。