【mysql】mysql的内连接和外连接小例子

解释名词:

1、内连接(自然连接): 只有两个表相匹配的行才能在结果集中出现

2、外连接: 包括

(1)左外连接(左边的表不加限制)

(2)右外连接(右边的表不加限制)

(3)全外连接(左右两表都不加限制)

3、创建student、score表如下

                                           (student表)

 

 


                                     (score表)

A:内连接sql
         select st.student_name,sc.object,sc.score,st.student_class
         from student st ,score sc where st.student_id=sc.student_id

        执行结果:

这个大家一般都司空见惯了。所以没什么可讲。内连接只是显示满足where后面的条件(st.student_id=sc.student_id)

B:左外连接sql

        select st.student_name,sc.object,sc.score,st.student_class
        from student st  left join score sc on st.student_id=sc.student_id
        执行结果:

左外连接是以左边的表(student st  left)student为主表,score为从表。在查询结果中全部展示主表的信息。
也就出现上图中Tom这个信息不全。因为从表中没有和Tom相匹配的信息,因此才会出现Null值填充。

C:右外连接

      select st.student_name,sc.object,sc.score,st.student_class
      from student st right  join score sc on st.student_id=sc.student_id

      执行结果:

   

   右连接刚好和做连接想法。因此就会出现上图的情况。

 

D:全外连接sql

    1. select st.student_name,sc.object,sc.score,st.student_class
     from student st  left join score sc on sc.student_id=st.student_id
    union
    select st.student_name,sc.object,sc.score,st.student_class
    from student st  RIGHT join score sc on sc.student_id=st.student_id

(本人使用mysql数据库,因为mysql暂时还不支持全外连接full的功能,但是可以用多个left来实现)

  2.select st.student_name,sc.object,sc.score,st.student_class
     from student st  full  join score sc on sc.student_id=st.student_id(此语句针对一般数据库)

  • 11
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值