• MySQL多表查询 三表查询 连接查询的套路


    多表查询 * 当我们的一条记录 分散不同的表中时,就需要进行多表查询 例如 一对一 一对多 多对多

    1.笛卡尔积查询  意思是将两个表中的所有数据 全部关联在一起
      例如 a表 有2条 b表有3条   一共6条
      会产生大量的错误数据 需要用添加来过滤
    select *from 表1,表2,....... where 过滤条件

    连接查询
    内连接查询 inner jon
      select *from 表1 join 表2 on 关系过滤条件
      两边的数据必须完全匹配成功才显示
        select *from emp join dept on dept.id = emp.dept_id;

    外连接查询 不常用(不应该出现这种没有正确关联的数据)
    左外连接   left join
      左边表的数据无论是否匹配成功 都要全部显示
        select *from emp left join dept on dept.id = emp.dept_id;
    右外连接   right join
      右边表的数据无论是否匹配成功 都要全部显示
        select *from emp right join dept on dept.id = emp.dept_id;
    全外连接
      mysql不支持   可以用合并查询union来 将 左外连接和右外连接合并
      select *from emp left join dept on dept.id = emp.dept_id
      union
      select *from emp right join dept on dept.id = emp.dept_id;

    on 专门用于筛选出正确的匹配关系 只能与join一起使用
    但是在join 中 可以把on 换成where
    反过来 在普通查询中不可以使用on
    通常在连接查询 join中推荐使用on

    连接查询解决问题的思路
    1.先联合查询   select *from emp join dept
    2.on 来筛选正确关系 on dept.id = emp.dept_id
    3. where 来进行额外的条件过滤 where dept.id = 1
    select *from emp join dept on dept.id = emp.dept_id where dept.id = 1;

    多对多关系的案例:
      egon老师教过哪些人?


    三表联查

    create table stu(id int primary key auto_increment,name char(10));

    create table tea(id int primary key auto_increment,name char(10));

     

    create table tsr(id int primary key auto_increment,t_id int,s_id int,

    foreign key(s_id) references stu(id),

    foreign key(t_id) references tea(id));

    insert into stu values(null,"张三"),(null,"李四");

    insert into tea values(null,"egon"),(null,"wer");

    insert into tsr values(null,1,1),(null,1,2),(null,2,2);

     


    select tea.name,stu.name from tea join tsr join stu
    on tea.id = tsr.t_id and stu.id = tsr.s_id
    where tea.name = "egon";

     

  • 相关阅读:
    Flesch Reading Ease(模拟)
    实验一:词法分析设计
    java—容器学习笔记
    [转载]马士兵Java视频教程 —— 学习顺序
    Java的安装过程
    编程之美初赛第一场
    RCC 2014 Warmup (Div. 2)
    ural 1017. Staircases(dp)
    ural 1012. K-based Numbers. Version 2(大数dp)
    ural 1009. K-based Numbers(简单dp)
  • 原文地址:https://www.cnblogs.com/tangda/p/10560863.html
Copyright © 2020-2023  润新知