【问题标题】:mySQL: how to go along 3 different tables, referring to different column in each table but using primary keysmySQL:如何处理 3 个不同的表,引用每个表中的不同列但使用主键
【发布时间】:2018-12-08 18:53:20
【问题描述】:

我试图找出哪些学校的学生在 2018 年没有完成考试。所以我设置了 3 个表格:ExamInfoExamEntryStudents。我将尝试使用ExamInfo 表从Students 表中获取信息,但我显然只想要2018 年未完成考试的学生信息。注意:我正在寻找参加过的学生,虽然没有完成考试,但通过这个特定的考试,您可以将完成的考试视为通过考试。

ExamInfo 内我有列:

ExamInfo_Date --when exam took place, using to get year() condition
ExamInfo_ExamNo --unique student exam ID used to connect with other tables
ExamInfo_Completed --1 if completed, 0 if not.
...

ExamEntry内有相关栏目:

ExamEntry_ExamNo --connected to ExamInfo table
ExamEntry_StudentId --unique studentId used to connect to Students table
ExamEntry_Date -- this is same as ExamInfo_Date if any relevance.
...

Students 内我有以下列:

Students_Id --this is related to ExamEntry_StudentId, PRIMARY KEY
Students_School --this is the school of which I wish to be my output.
...

我希望我的输出只是列出所有有学生在 2018 年未完成考试的学校。虽然我的问题是从 ExamInfo 表中查找学生未完成考试的学校.

到目前为止,我已经:

SELECT a.Students_School, YEAR(l.ExamInfo_Date), l.ExamInfo_Completed
FROM ExamInfo l ??JOIN?? Students a
WHERE YEAR(l.ExamInfo_Date) = 2018
AND l.ExamInfo_Completed = 0
;

我什至不确定是否需要查看ExamEntry 表。我确定我打算使用连接,但不确定如何正确使用它。此外,对于我的 3 个不同的 SELECT 列,我只希望输出 Students_School 列:

Students_School
---------------
Applederry
Barnet Boys
...

【问题讨论】:

  • 和那个连接中的 ON 子句?

标签: mysql sql join foreign-keys primary-key


【解决方案1】:

显然,您需要一个JOIN——实际上是两个。您的表有 examsstudents 和一个表示这些实体之间的多对多关系的联结/关联表。

所以,我希望FROM 子句看起来像:

FROM ExamInfo e JOIN
     ExamEntry ee
     ON ee.ExamEntry_ExamNo = e.ExamNo JOIN
     Students s
     ON ee.ExamEntry_StudentId = s.Students_Id

【讨论】:

    猜你喜欢
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    相关资源
    最近更新 更多