zoukankan      html  css  js  c++  java
  • SQL语句中的左连接、右连接、内连接的理解心得

    本人数据库文盲一个,关于连接的讲解在网上有很多,但是我总是看不懂,所以就自己总结了个自己能看懂的,如果有错误望大家指出。
    假设两个表 
    A                B
    id  name      id   name   mid
    1   a          1   aa     2
    2   b          2   bb     null 
    3   c          3   cc     5
    4   d          8   ff     1
                   9   ee     4
    ->左连接
    语句为
    select aa.id aid,aa.name aname bb.id bid,bb.name bname,bb.mid from 
    (select * from A)aa
    left join
    (select * from B)bb
    on aa.id = bb.id;
    结果为:
    aid   aname   bid   bname   bmid
    1     a       1     aa      2
    2     b       2     bb      null
    3     c       3     cc      5
    4     d       null  null    null
     
    从结果中可以看出,表A左连接表B时,以左边的表为基准进行查找,此时的基准表为表A,从结果中看出,A表的记录全部都在结果中,B表的记录只有那么足条件aa.id = bb.id才在结果中。倘若没有满足条件的A表记录,A中的记录也会也会全部出现在结果中,相应的B表数据将会是NULL。
     
    ->右连接
    语句为
    select bb.id bid,bb.name bname,bb.mid,aa.id aid,aa.name aname from
    (select * from A)aa
    right join
    (select * from B)bb
    on aa.id = bb.id;
    结果为:
    bid   bname   mid   aid   aname
    1     aa      2     1     a
    2     bb      null  2     b
    3     cc      5     3     c
    8     ff      1     null  null
    9     ee      4     null  null
     
    从结果中不难看出,表A右连接表B时,以右边的表为准进行结果查找,此时的基准表为B,从结果中看出,B表的记录都出现在了结果中,A表中的记录只有满足筛选条件的结果才出现在结果中,像id号为4的记录并没有出现在查询结果中,对于没有满足查询条件的B表的记录则会显示在结果中,相应的A表的字段会以NULL填充。
    ->内连接
    语句为
    select bb.id bid,bb.name bname,bb.mid,aa.id aid,aa.name aname from
    (select * from A)aa
    inner join
    (select * from B)bb
    on aa.id = bb.id;
    结果为:
    bid   bname   mid   aid   aname
    1     aa      2     1     a
    2     bb      null  2     b
    3     cc      5     3     c
     
    同样,从结果中我们可以很直观的看到内连接进行的查询就是将两个表中的都满足条件的条目提出来作为结果。A表中id号为4的记录在B表中没有与之id号相同的记录,则A表的该条记录也没有出现在结果中,同样B表中id号为8、9的记录也没有出现在结果中。
  • 相关阅读:
    图片验证码, 登录, 注销, 修改密码
    注册页面及注册功能实现
    高级配置文件, csrf, django settings源码, django auth模块, 文件配置的插拔式设计
    cookie操作, session操作, django中间件
    半自动创建多对多关系表, forms组件
    sweetalert, bulk_create, 分页器
    orm查询优化, MVC与MTV, choices参数, ajax
    聚合查询, 分组查询, F与Q查询, 常见字段及参数, 自定义Char字段, 事务操作
    Contest2058
    ACM版《孔乙己》
  • 原文地址:https://www.cnblogs.com/upcyaya/p/2695156.html
Copyright © 2011-2022 走看看