• MySQL的内外连接


    📟作者主页:慢热的陕西人

    🌴专栏链接:MySQL

    📣欢迎各位大佬👍点赞🔥关注🚓收藏,🍉留言

    本博客主要内容主要介绍了MySQL中的内外连接

    在这里插入图片描述

    MySQL的内外连接

    1.内连接

    内连接实际上就是利用where子句对两种表形成的笛卡儿积进行筛选,我们前面学习的查询都是内连接,也是在开发过程中使用的最多的连接查询

    语法:

    select 字段 from 表1 inner join 表2 on 连接条件 and 其他条件;
    
    • 1

    案例:显示SMITH的名字和部门名称

    -- 用前面的写法
    select ename, dname from EMP, DEPT where EMP.deptno=DEPT.deptno and
    ename='SMITH';
    -- 用标准的内连接写法
    select ename, dname from EMP inner join DEPT on EMP.deptno=DEPT.deptno and
    ename='SMITH';
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2.外连接

    外连接分为左外连接和右外连接

    2.1左外连接

    如果联合查询,左侧的表完全显示我们就说是左外连接。
    语法:

    select 字段名 from 表名1 left join 表名2 on 连接条件
    
    • 1

    案例:

    -- 建两张表
    create table stu (id int, name varchar(30)); -- 学生表
    insert into stu values(1,'jack'),(2,'tom'),(3,'kity'),(4,'nono');
    create table exam (id int, grade int); -- 成绩表
    insert into exam values(1, 56),(2,76),(11, 8);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 查询所有学生的成绩,如果这个学生没有成绩,也要将学生的个人信息显示出来

      -- 当左边表和右边表没有匹配时,也会显示左边表的数据
      select * from stu left join exam on stu.id=exam.id;
      
      • 1
      • 2

    2.2右外连接

    如果联合查询,右侧的表完全显示我们就说是右外连接。

    语法:

    select 字段 from 表名1 right join 表名2 on 连接条件;
    
    • 1

    案例:

    • 对stu表和exam表联合查询,把所有的成绩都显示出来,即使这个成绩没有学生与它对应,也要显示出来

      select * from stu right join exam on stu.id=exam.id;
      
      • 1

    练习:

    • 列出部门名称和这些部门的员工信息,同时列出没有员工的部门

      方法一:
      select d.dname, e.* from dept d left join emp e on d.deptno=e.deptno;
      方法二:
      select d.dname, e.* from emp e right join dept d on d.deptno=e.deptno;
      
      • 1
      • 2
      • 3
      • 4

    到这本篇博客的内容就到此结束了。
    如果觉得本篇博客内容对你有所帮助的话,可以点赞,收藏,顺便关注一下!
    如果文章内容有错误,欢迎在评论区指正

    在这里插入图片描述

  • 相关阅读:
    MindSpore Graph Learning
    【算法基础】用数组模拟栈和队列
    全局异常处理器
    [附源码]java毕业设计音乐交流平台
    【GitLab、GitLab Runner、Docker】GitLab CI/CD 应用
    arm-linux pinctrl 和 gpio 子系统
    CentOS安装htop工具
    空间占用计算
    Windows服务器如何防止黑客入侵的安全设置
    LotusScript中的命名文档
  • 原文地址:https://blog.csdn.net/weixin_61766635/article/details/137891416