首页 > 数据库技术 > 详细

SQL的各种连接--自联结,内连接,外连接,交叉连接

时间:2019-06-28 13:09:06      阅读:77      评论:0      收藏:0      [点我收藏+]

1、准备两个表:Student,Course,其中student.C_S_Id=Course.C_Id(即Student 表中的 C_S_Id 字段为外键列,关联的是 Course 表的 C_Id 主键列)

技术分享图片

2、内连接(table1 inner join table2 on 条件表达式):满足on条件表达式,内连接是取满足条件表达式的两个表的交集(其中inner可以省略);

  select * from Student s

  inner join Course c on s.C_S_Id=c.C_Id

 结果如下:

技术分享图片

3、外连接(outer join)分为:左外连接(left outer join / left join),右外连接(right join / right outer join)和全外连接(full join / full outer join)

  (1)左外连接(table1 left join table2 on 条件表达式):满足on条件表达式,左外连接是以左表为准,返回左表所有的数据,与右表匹配的则有值,

   没有匹配的则以空(null)代替。

  select * from Student s

  left join Course c on s.C_S_Id=c.C_Id

  结果如下:

技术分享图片

  (2)右外连接(table1 right join table2 on 条件表达式):满足on条件表达式,右外连接是以右表为准,返回右表所有的数据,与左表匹配的则有值,

   没有匹配的则以空(null)代替。

  select * from Student s

  right join Course c on s.C_S_Id=c.C_Id

  结果如下:

技术分享图片

  (3)全外连接(table1 full join table2 on 条件表达式):满足on条件表达式,返回两个表符合条件的所有行,a表没有匹配的则a表的列返回null,

      b表没有匹配的则b表的列返回null(即返回的是左外连接和右外连接的并集)。

  select * from Student s

  full join Course c on s.C_S_Id=c.C_Id

  结果如下:

技术分享图片

4、交叉连接(table1 cross join table2):交叉连接将返回被连接的两个表的笛卡尔乘积,返回结果的行数等于两个表的行数的乘积。

 不加条件的交叉连接SQL语句:

  select * from Student s

  cross join Course c

 加上条件返回满足条件表达式的两个表的行(交叉连接加条件只能用where):

  select * from Student s

  cross join Course c

  where s.C_S_Id=c.C_Id;

 结果如下:

技术分享图片

5、自连接:表与表自己连接此时需要给表取别名,而且后面加条件时也只能用where,这点同全外连接一样。

  select s1.S_Name,s2.S_age

  from Student s1,Student s2

  where s1.S_BirthDate=s2.S_BirthDate

 

SQL的各种连接--自联结,内连接,外连接,交叉连接

原文:https://www.cnblogs.com/hdc520/p/11101849.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!