SQL外连接

时间:2012-11-16 04:50:39

标签: mysql sql

三个表课程,注册,学生

学生中的

firstname,lastname,studentid,major,admitdate,graddate,gender,dob

注册中的列

courseid,studentid

课程中的列

coursenumber,coursename,credits

选择我需要修改的语句

select lastname as 'Last Name',sum(credits) as 'Credits Registered For' from students   as s
inner join registration as r on s.studentid = r.studentid
inner join courses as c on c.coursenumber = c.courseid
group by last name;

实验室的问题是......修改上一个查询以显示所有学生,即使他们没有注册课程。你应该有14行。未注册的学生将在输出中显示NULL。

我知道这需要某种类型的外部联接,但我并没有完全掌握这些联接,我已经在这里和其他网站上阅读过多个帖子,但似乎无法弄明白。

2 个答案:

答案 0 :(得分:3)

使用LEFT JOIN

select  lastname as 'Last Name',
        sum(credits) as 'Credits Registered For' 
from    students   as s
        LEFT join registration as r on s.studentid = r.studentid
        LEFT join courses as c on c.coursenumber = r.courseid
group by last name;

答案 1 :(得分:0)

尝试

SELECT  s.lastname AS 'Last Name',
        sum(c.credits) AS 'Credits Registered For' 
FROM    students    s
        LEFT JOIN registration  r ON (s.studentid = r.studentid)
        INNER JOIN courses  c ON (c.coursenumber = r.courseid)
GROUP BY lastname;

注意:在为表名提供别名时无需使用AS