从两个表中加入两个外键值

时间:2018-03-08 18:03:41

标签: sql join subquery inner-join

我有下表;

Course(cname, ccode, credit, dept) // course table.
Section(sno, ccode, semestr, year, prof); // course and lectures according to year and semester value.
Prerequisite(ccode, precode) // prerequisite for any course.

问题:

列出2012年开设的课程和必修课程 - 两者的代码和名称

我尝试通过加入来解决它。

select c.ccode, c.cname, p.precode from Course as c 
inner join prerequisite as p on p.ccode=c.ccode;

查询返回下面的元组。

Course | Name                 | Pre. code  
B201   | software engineering | B101  
B202   | operating system     | B101  
H202   | civil law            | H102

如何获取必备课程名称及其代码的名称? 期望的结果必须低于;

Course    | Name                 | Pre. code  | Pre. name
B201      | software engineering | B101       | aaaaa   
B202      | operating system     | B101       | aaaaa 
H202      | civil law            | H102       | bbbb

2 个答案:

答案 0 :(得分:1)

我使用您的查询,并添加EXISTS子句。基本上逻辑在EXISTS子句中,我发现所有课程都在2012年有部分。然后EXISTS将只返回与EXISTS子句匹配的课程。

SELECT c.ccode, c.cname, p.precode 
FROM Course c 
JOIN prerequisite p ON p.ccode = c.ccode
WHERE EXISTS (
    SELECT 1
    FROM Section
    WHERE ccode = c.ccode AND year = '2012'
)

或者如果使用JOIN

SELECT c.ccode, c.cname, p.precode, cp.cname
FROM Course c 
JOIN prerequisite p ON p.ccode = c.ccode
JOIN Course cp ON cp.ccode = p.precode
JOIN Section s ON s.ccode = c.ccode
WHERE s.year = '2012'

答案 1 :(得分:1)

select c.ccode, c.cname
     , p.precode, cp.name as preName 
  from Course as c 
  join prerequisite as p 
    on p.ccode = c.ccode 
  join Cource cp 
    on cp.ccode = p.precode