码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2019-03-19 20:05:13      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:匹配   contain   显示   ...   auto   额外   查询   from   过滤   

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

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";

 

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

标签:匹配   contain   显示   ...   auto   额外   查询   from   过滤   

原文地址:https://www.cnblogs.com/tangda/p/10560863.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!