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

来源:互联网 发布:李嘉诚撤资 知乎 编辑:程序博客网 时间:2024/05/16 07:31

内连接 :连接的数据表相对应的匹配字段完全相等的连接。连接关键字是 inner join

外连接 :分为左外连接与右外连接、全连接。

    左连接的结果集包括指定的左表全部数据与匹配的右表数据,右表中没匹配的全为空值.关键字 left join

    右连接的结果集包含指定的右表全部数据与匹配的左边数据,左边中没匹配的全为空值.关键字 right join

全连接:返回左右数据表的所有行.关键字 full join

自然连接:不需要人为指定连接字段,自然会自动找同名字段进行连接,会删除连接后的重复列。 关键字 natural

解释名词:

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(此语句针对一般数据库)


refer:  http://blog.csdn.net/zlxdream815/article/details/8208509

原创粉丝点击