• Mysql常用的几种join连接方式


    1.首先准备两张表

    部门表:

      

    员工表:

      

    以下我们就对这两张表进行不同的连接操作

    1.内连接

      作用: 查询两张表的共有部分

       语句:Select <select_list> from tableA A Inner join tableB B on A.Key = B.Key

       示例:SELECT * from employee e INNER JOIN department d on e.dep_id = d.id;
       结果显示:通过这个查找的方法,我们没有查到id为8的数据

         

    2.左连接

        作用:把左边表的内容全部查出,右边表只查出满足条件的记录

      语句:Select <select_list> from tableA A Left Join tableB B on A.Key = B.Key  

      示例:SELECT * from employee e LEFT JOIN department d on e.dep_id = d.id;

      结果显示:

        

    3.右连接

       作用:把右边表的内容全部查出,左边表只查出满足条件的记录

      语句:Select <select_list> from tableA A Left Join tableB B on A.Key = B.Key

      示例:SELECT * from employee e RIGHT JOIN department d on e.dep_id = d.id;
      结果显示:

        

    4.查询左表独有数据

      作用:查询A的独有数据

      语句:Select <select_list> from tableA A Left Join tableB B on A.Key = B.Key where B.key IS NULL   

      示例:SELECT * from employee e LEFT JOIN department d on e.dep_id = d.id WHERE d.id IS NULL;
      结果显示:

        

    5.查询右表独有数据

      作用:查询B的独有数据

      语句:Select <select_list> from tableA A Right Join tableB B on A.Key = B.Key where A.key IS NULL   

      示例:SELECT * from employee e RIGHT JOIN department d on e.dep_id = d.id WHERE e.id IS NULL;

      结果显示:

        

    6.全连接

       作用:查询两个表的全部信息

      语句:Select <select_list> from tableA A Full Outter Join tableB B on A.Key = B.Key

      注:Mysql 默认不支持此种写法 Oracle支持       可以使用将左连接与右连接结合起来作为全连接

      示例:  

        SELECT * from employee e LEFT JOIN department d on e.dep_id = d.id

        UNION

        SELECT * from employee e RIGHT JOIN department d on e.dep_id = d.id

      结果显示:

        

     7.查询左右表各自的独有的数据

      作用:查询A和B各自的独有的数据

      语句:Select <select_list> from tableA A Full Outter Join tableB B on A.Key = B.Key where A.key = null or B.key=null    

      示例:
        SELECT * from employee e LEFT JOIN department d on e.dep_id = d.id WHERE d.id is NULL

        UNION

        SELECT * from employee e RIGHT JOIN department d on e.dep_id = d.id WHERE e.dep_id is NULL

      结果显示:

        

  • 相关阅读:
    【Docker】命令 restart
    【Docker】命令 rename
    小知识点笔记一(原始版)
    Java常用类——匿名对象
    Java常用类——Arrays工具类
    Java常用类——Scanner类
    Python怎么测试异步接口
    接口测试面试题
    Pycharm使用常见问题
    接口测试命令Httpie的使用
  • 原文地址:https://www.cnblogs.com/pcliu/p/11099761.html
Copyright © 2020-2023  润新知