zoukankan      html  css  js  c++  java
  • mysql 内连接和外连接查询

    一、内连接查询 (笛卡儿积)

    内联接查询inner join,mysql可以简写为join

    二、外连接查询

    左外联接查询left outer join,mysql可以简写为left join
    右外联接查询right outer join,mysql可以简写为right join

    举个栗子:

    创建两张表t1,t2,并插入一些数据

    create table t1(
        cid varchar(10),
        city varchar(10),
        primary key(cid)
    )
    insert into t1 values('tedu','bj'),('tx','bj'),
    ('jd','sh'),('bd','bj')
    
    create table t2(
        id int,
        customer varchar(10),
        primary key(id)
    )
    insert into t2 values(1,'tedu'),(2,'tedu'),(3,'tx'),(4,'jd'),(5,Null)

    1.t1和t2做内联接查询,得到t1和t2的迪卡尔积

    select * from t1 join t2;

    2.在t1和t2的迪卡尔积上做了筛选,筛选的条件就是t1和t2中有关联的列

    select * from t1 join t2
    on t1.cid = t2.customer;

    3.在t1和t2筛选过的迪卡尔积上,t1和t2做左外联接查询

    select * from t1 left join t2
    on t1.cid = t2.customer;

    4.在t1和t2筛选过的迪卡尔积上,t1和t2做右外联接查询

    select * from t1 right join t2
    on t1.cid = t2.customer;

    总结:一.A表和B表内连接就是把A表的每条记录和B表的每条记录做完全组合,如果A表中有4条记录,B表中有5条记录,那么A表和B表内连接后产生的大表就是4*5=20条记录。

               二.外连接是在内连接的基础上加上left或者right,外连接包含两点,例如select * from t1 left join t2  on t1.cid = t2.customer 这样做外连接

         1.t1表中的每条记录都要显示出来,如果在t2没有与之对应的,则显示Null;

                  2.t2表中如果有多条记录都可以和t1表中对应,则把这多条记录都显示出来。

  • 相关阅读:
    Flutter 路由管理
    SpringMVC 集成 MyBatis
    关于windows下安装mysql数据库出现中文乱码的问题
    md5.digest()与md5.hexdigest()之间的区别及转换
    MongoDB基础命令及操作
    redis相关操作&基本命令使用
    python中mysql主从同步配置的方法
    shell入门基础&常见命令及用法
    ORM总结
    多任务:进程、线程、协程总结及关系
  • 原文地址:https://www.cnblogs.com/hooo-1102/p/11943745.html
Copyright © 2011-2022 走看看