簡體   English   中英

mySQL:如何遍歷3個不同的表,引用每個表中的不同列,但使用主鍵

[英]mySQL: how to go along 3 different tables, referring to different column in each table but using primary keys

我試圖找出哪些學校的學生在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
...

顯然,您需要一個JOIN實際上是兩個。 您的表中包含考試學生和一個聯結/關聯表,該表表示這些實體之間的多對多關系。

因此,我希望FROM子句看起來像:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM