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
我基本上试图获得所有可用课程的结果集,其中一个是特定学生注册的,哪一个不是,所以我将能够将其显示为我们可以提供给学生的课程。
我尝试过这个查询的许多变体并进行了一些研究。我并不是要求代码,但是一些指导会非常棒。在尝试同时处理项目的其他部分时,我已经坚持了几天。
任何帮助深表感谢。提前致谢。
没有找到相关结果
已邀请:
3 个回复
荒劫娇噬
峨躬坎抬焚
这应该工作(假设mysql允许您在连接逻辑上有多个谓词,认为它确实有,但没有要测试的实例) 如果失败,您可以加入适用于您的限制的子查询。
社攻取墟槽
这可能需要一些调整,我不确定确切的语法,但它可能是如何获得你需要的想法。