使用 Junction Table 加入 MANY to MANY

Joining MANY to MANY with Junction Table

好的,此时我只是不知道下一步该做什么。我刚开始学习 mySQL 中的连接,我想做的是通过它的连接 table (Many-to-Many) 关系连接 2 table。但是我下面的 http://www.w3schools.com/sql/sql_join_left.asp 中的例子并没有说明 MANY-TO-MANY tables.

我有 3 个 table。

1.) 课程

2.) 课程科目 --the junction table

3.) 主题

课程

id PK
name
description
yearLevel
syStart
syEnd

课程科目 --junction table

id PK
curriculumId FK
subjectCode FK

主题

code PK
name
yrLevel
description

期望的结果是显示主题代码主题名称主题描述subject yearlevel 如果提供或如果在过程调用中给出 curriculum namecurriculum year level

这就是我所做的。

CREATE PROCEDURE `getCurriculumSubjects` (IN p_CurcName varchar(50),IN p_yrLevel varchar(50))
BEGIN
    SELECT `subject`.`code`,`subject`.`name`,`subject`.yrLevel, `subject`.description
    FROM `subject`

    LEFT OUTER JOIN curriculumsubjects
    ON `subject`.`code` = curriculumsubjects.subjectCode

    LEFT OUTER JOIN curriculum
    ON curriculum.id = curriculumsubjects.curriculumId
    WHERE curriculumsubjects.id = (SELECT id FROM curriculum WHERE `name` = p_CurcName AND yearLevel = p_yrLevel);

END

目前 curriculum table 上有 1 条记录,subject table 上有 2 条记录。

课程Table截图

主题Table截图

课程主题Table 屏幕截图

但是当我 运行 脚本时,我什么也没得到。

我的意思是,如何正确使用左连接来解决这个问题? 我可以加入更多 table 而不是 2 个吗?

如果有任何帮助,我将不胜感激。

提前致谢。

我认为这可以实现您的要求:

select s.code, s.name, s.description, s.yrLevel
from subject s
inner join curriculumsubject cs on s.code = cs.subjectCode
inner join curriculum c on cs.curriculumId = c.ID
where c.name = p_CurcName and c.yearLevel = p_yrLevel

我认为左连接不合适,除非您想 return 主题的空值,当参数值存在于课程表中,但没有 link 主题。如果您只想 return 有匹配主题的行,那么内部联接是正确的解决方案。