MySQL多表查询 三表查询 链接查询的套路

多表查询 * 当咱们的一条记录 分散不一样的表中时,就须要进行多表查询 例如 一对一 一对多 多对多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老师教过哪些人?


三表联查sql

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

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

 

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

foreign key(s_id) references stu(id),io

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

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

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

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

 


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";
相关文章
相关标签/搜索