使用连接表将MANY连接到MANY

时间:2016-06-09 14:00:14

标签: mysql sql join left-join inner-join

好的,此时我还不知道接下来该做什么。我刚刚开始学习mySQL中的连接,而我想要做的就是通过它的联结表(Many-to-Many)关系加入2个表。但是我所关注的http://www.w3schools.com/sql/sql_join_left.asp中的示例并没有说明MANY-TO-MANY个表格。

我有3张桌子。

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

所需结果是显示主题代码主题名称主题描述主题年级(如果提供)或者如果在程序调用中给出了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表上有一条记录,subject表上有2条记录。

CURRICULUM表格截图

enter image description here

SUBJECT表格截图

enter image description here

CURRICULUMSUBJECT表格截图

enter image description here

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

enter image description here

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

我很感激任何帮助。

提前致谢。

1 个答案:

答案 0 :(得分:1)

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

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

我不认为左连接是合适的,除非您想要在课程中存在参数值时为主题返回空值,但是没有指向主题的链接。如果只想在匹配主题的位置返回行,则内连接是正确的解决方案。

相关问题