sql多表连接查询

初始表环境如下:

表1:student


表2:course


1.外链接:

    又分为:左连接、右连接、完全外连接

    左连接:select * from student left join course on student.ID=course.ID

    查询结果为:

                        

    右连接:select * from student right join course on student.ID=course.ID

    查询结果为:

                        

    完全外连接:select * from student full join course on student.ID=course.ID

    查询结果为:

                        

2.内连接:

    sql语句为:select * from student inner join course on student.ID=course.ID

        相当于:select * from student,course where student.ID=course.ID

    查询结果为:

                        

3.交叉连接:

    交叉连接语句分为两种:

    (1)交叉连接语句中没有where子句,结果为所涉及表的笛卡尔积(结果集的行数=第一张表的行数*第二张表的行数)

    sql语句:select * from student cross join course

    查询结果为:

                        

    (2)交叉连接语句中有where子句,此时结果与inner join相同

4.两表关系为一对多,多对一或多对多时的连接

    表A:

                         

    表B:

                        

    表C:

                        

由上3张表结构可知,一个学生可以选多门课程,一门课程可被多名学生选择,因此学生表student和课程表course之间是多对多的关系。当两张表为多对多关系的时候,我们需要建立一个中间表student_course,中间表至少要有两表的主键,当然还可以有别的内容。

如果我们想查询所有学生的选课情况:

sql语句:select s.Name,c.Cname from student_course as sc left join student as s on s.Sno = sc.Sno left join course as c on c.Cno = sc.Cno

查询结果为:

                        


参考链接:https://blog.csdn.net/mr_tim/article/details/51135377

(微笑脸)

猜你喜欢

转载自blog.csdn.net/liu123641191/article/details/80375233