我通常閱讀其他線程,這是我的第一個問題。開始;Mysql幫助 - 左加入
我想建立一個涉及兩個表,課程表和studentsLink表的查詢。 StudentsLink表格描述了學生和課程之間的聯繫。表格如下;
Course
courseID(bigint) - PK
courseName (varchar)
courseInstructor (varchar)
StudentsLink
courseID(bigint) - PK
StudentID(bigint) - PK
Below is some sample data;
course table
ID | courseName| courseInstructor
----------------------------------
1 | Algebra 1 | Mike
2 | English 2 | James
3 | English 3 | John
4 | Algebra 2 | Mike
5 | History 1 | Tony
Studentlink table
studentID | courseID
----------------------
100 | 2
101 | 3
102 | 3
102 | 4
103 | 4
100 | 1
103 | 3
103 | 2
,如果我一直在尋找的學生數量期望的結果是下面給出的103
ID | courseName| courseInstructor |StudentID | CourseID
---------------------------------------------------------
1 | Algebra 1 | Mike | NULL | NULL
2 | English 2 | James | 103 | 2
3 | English 3 | John | 103 | 3
4 | Algebra 2 | Mike | 103 | 4
5 | History 1 | Tony | NULL | NULL
,我至今是下面的查詢;
SELECT *
FROM course
LEFT JOIN studentLink
ON course.courseID = studentLink.courseID
WHERE studentLink.studentID = 103 OR (studentLink .studentID IS NULL AND studentLink.courseID IS NULL)
ORDER BY studentLink.courseID DESC
基本上,我試圖讓設置了所有可用的課程,哪一個是特定的學生在註冊的結果,哪一個是他不是這樣我就可以顯示它作爲一門課程,其我們可以提供給學生。
我已經嘗試了這個查詢的許多變化,並做了一些研究。我不完全要求編碼,但一點指導會很棒。在嘗試同時處理項目的其他部分時,我一直堅持這幾天。
任何幫助,非常感謝。提前致謝。