• MySQL 连接查询(多表查询 二)


    基本介绍

    作用:连接查询(Join)操作,用于联结多个表以获取更全面和准确的数据

    基本分类:

    • 内连接:相当于查询A、B交集部分数据(去掉迪卡尔积无效组合)
    • 外连接:
      • 左外连接:查询左表所有数据,以及两张表交集部分数据
      • 右外连接:查询右表所有数据,以及两张表交集部分数据
    • 自连接:当前表与自身的连接查询,自连接必须使用表别名

    内连接

    语法(两种语法不同,作用相同):

    隐式内连接select 字段列表 from 表1 , 表2 where 条件 ... ;

    显式内连接:select 字段列表 from 表1 [  inner ] join 表2 on 连接条件 ... ;

    1. -- 内连接 查询员工与部门关联信息
    2. select employees.name 员工名字, departments.name 部门名称
    3. from employees
    4. inner join departments
    5. on employees.department_id = departments.id

    外连接(左外连接和右外连接可以相互替换)

    左外连接

    语法:select 字段列表 from 表1 left [ outer] join 表2 on 条件 ... ;

    1. -- 左外连接 从员工表查询对应部门
    2. select employees.name, departments.name 部门名称
    3. from employees
    4. left join departments
    5. on employees.department_id = departments.id
    6. limit 5,6;

    右外连接

    语法:select 字段列表 from 表1 right [ outer] join 表2 on 条件 ... ;

    1. -- 右外连接 从部门表查询对应员工信息
    2. select employees.name, departments.name 部门名称
    3. from employees
    4. right join departments
    5. on employees.department_id = departments.id
    6. limit 5,6;

    全连接

    MySQL不支持全连接的关键字(full join),但可以通过左连接和右连接的组合实现全连接

    1. -- 全连接 查询员工和对应部门的对应关系
    2. select employees.name, departments.name 部门名称
    3. from employees
    4. left join departments
    5. on employees.department_id = departments.id
    6. union
    7. select employees.name, departments.name 部门名称
    8. from employees
    9. right join departments
    10. on employees.department_id = departments.id
    11. limit 5,8;

    自连接

    语法:select 字段列表 from 表A 别名A join 表A 别名B on 条件 ... ;

    1. -- 自连接 查询每个员工和对应的领导名字
    2. SELECT e1.name AS 员工姓名, e2.name AS 上级领导姓名
    3. FROM employees e1
    4. INNER JOIN employees e2
    5. ON e1.manager_id = e2.id;

    也可以实现联合查询:

    SELECT 字段列表 FROM 表A 条件 ...
    union [ all]
    SELECT 字段列表 FROM 表B 条件....;

    1. -- 查询薪水小于5000 或 年龄大于50的员工
    2. select * from employees where salary < 5000
    3. union
    4. select * from employees where age > 50;

    注意点:

    • 对于联合查询的多张表的列数必须保持一致,字段类型也需要保持一致。
    • union all 会将全部的数据直接合并在一起(不去重),union 会对合并之后的数据去重。

    上一篇:MySQL 多表关系(多表查询 一)

    下一篇:MySQL 子查询(多表查询 三)

  • 相关阅读:
    鸡尾酒学习——薄荷夏日
    微服务基础技能 SpringBoot详解!
    Apache 服务器的搭建和配置
    C# 嵌入式数据库LiteDB
    Linux Terminal 下工具栏显示设置
    测试设计场景题
    GOT Online For Unreal | 支持GPU Counter、DrawCall和Triangle、功率
    Spring——AOP
    微信群拼团活动链接如何制作?教你一招,新手1分钟做一个拼团链接
    Python使用大连理工情感本体提取文本的情感倾向
  • 原文地址:https://blog.csdn.net/DU9999999/article/details/133297683