zoukankan      html  css  js  c++  java
  • SQL查询中连接--学习

    一、开头说

    不出意外,还是先说下SQL中所有的联接类型:

    内连接外连接(左连接、右连接 、全连接)、交叉连接

    然后接下来就是依次学习下各种连接的使用效果

    二、各种连接秀

    首先准备两张表

     
    学生表:student(id,姓名,年龄,性别 )
     
    成绩表:score(id,学生id,成绩)

    1、内连接 inner join……on

    select student.* ,Score.* from student inner join Score on student.id=Score.sid
    查询结果如下:
     
     
    关系如下图:
     
    总结:inner join取两表的交集。

    2、外连接

    外连接包括 左连接、右连接、全连接  (left|right | full outer join ……on),其中outer可以省略
     
    (1)左连接(left join ……on)
    select student.* ,Score.* from student left join Score on student.id=Score.sid
    查询结果如下:
     
    关系如下图:
     
    总结:left join 以左表为准,查询出左表的所有数据,右表中有对应的则显示出来,没有对应的则显示为null.
    注:A left join B on  与  A,B where  有相同效果,如下:
    select student.* ,Score.* from student inner join Score on student.id=Score.sid
    select student.* ,Score.* from student,Score where student.id=Score.sid
     
     
    (2)右连接(right join ……on)
    select student.* ,Score.* from student right join Score on student.id=Score.sid
     
    关系如下图:
     
    总结:right join 以右表为准,查询出右表的所有数据,左表中有对应的则显示出来,没有对应的则显示为null.
     
    (3)全连接(full join ……on)
    select student.* ,Score.* from student full join Score on student.id=Score.sid
     
    总结:full join 是为left和right的集合,某表中某一行在另一表中无匹配行,则相应列的内容为NULL。

    3、交叉连接(cross join),注意没有on条件

    select student.* ,Score.* from student cross join Score
     

    叉联接也称作笛卡尔积。相当于两个表中的所有行进行排列组合。

    若表a有X行,表b有Y行,则将返回XY行记录。

    说明:使用select * from student,Score语句时,同样会做笛卡尔积生成虚拟表然后查询会所有条数据

     

  • 相关阅读:
    Pymongo
    asp.net mvc4 使用java异步提交form表单时出现[object object] has no method ajaxSubmit
    C# Activator.CreateInstance()
    GridView中某一列值的总和(web)
    02.[WPF]如何固定窗口的大小
    01.WPF中制作无边框窗体
    C#.net时间戳转换
    org.springframework.beans.factory.BeanCreationException: 求教育!
    log4Net配置详解
    SQL语句-创建索引
  • 原文地址:https://www.cnblogs.com/clarenceyang/p/10716036.html
Copyright © 2011-2022 走看看