多表查询+多对多 三表连查+子查询

多表查询
在多个表中查询需要的数据
例如:有班级表 和学生表
给你已给班级名称 请查询所有的学员数据
先查班级表 得到一个班级的id 再根据id去学院表查询对应的学员

准备数据:
create table emp (id int,name char(10),sex char,dept_id int);
insert emp values(1,"大黄","m",1);
insert emp values(2,"老王","m",2);
insert emp values(3,"老李","w",30);

create table dept (id int,name char(10));
insert dept values(1,"市场");
insert dept values(2,"财务");
insert dept values(3,"行政");

多表查询的方式
1.笛卡尔积查询
什么是笛卡尔积,用坐标中的一条记录 去链接另一张表的所有记录
就像是把 两张表的数据做了一个乘法
这将导致 产生大量的无用重复数据
我们要的效果是:员工表中的部门id 与 部门表中的id相同 就拼接在一起
用 where 筛选出正确的数据
select *from emp,dept where emp.dept_id = dept.id;

on关键字
作用 用于多表查询是 进行条件限制
select *from emp,dept on emp.dept_id = dept.id; 这是错误的语法 因为 on 它只能用在专门多表查询语句中


2.内连接查询
inner join
select *from emp inner join dept on emp.dept_id = dept.id;

# 查询 所有的员工以及他们所属的部门信息
3.左外连接
left join
左边表中的数据完全显示 右边表中的数据匹配上才显示
select *from emp left join dept on emp.dept_id = dept.id;

# 查询 所有的部门以及他们所有的员工信息
4.右外连接
right join
左边表中的数据匹配上才显示 右边表中的数据完全显示
select *from emp right join dept on emp.dept_id = dept.id;

# 在一个表中 显示多个表中的所有数据
5. 全外链接
full join mysql不支持 oracle支持
可以通过union 间接实现
union 表示合并查询 意思是把多个查询结果合并在一起显示
要求是 被合并的表结构必须相同
默认去除重复

合并但是不去除重复
union all

select *from emp right join dept on emp.dept_id = dept.id
union
select *from emp left join dept on emp.dept_id = dept.id;




总结:多表链接 在书写时 按照填空来书写 如果左边要全部显示 用left join
右边全部显示 用right join
全部显示 把左链接的结果和右链接的结果 合并
当然 也可以更多表一起查 但是 没有意义 并且你要尽量避免 太多表 一起查
最多三张 在多对多的时候

select *from emp left join dept left join xxtable on emp.dept_id = dept.id;

create table tec(id int,name char(10));
insert into tec value(1,"egon");
insert into tec value(2,"yyh");

create table stu(id int,name char(10));
insert into stu value(1,"大傻");
insert into stu value(2,"中傻");
insert into stu value(3,"小傻");
create table s_t(s_id int,t_id int);
insert into s_t value(1,2);
insert into s_t value(2,2);
insert into s_t value(3,1);

需求 找出 yyh 这个老师 教过的学生信息
思路:
第一步 到关系表中 去查询 哪些老师教过哪些学生(学生的id) 形成了一个临时表
第二步 将上一步得到临时表 与 学生表进行连接
第三步 加上额外的筛选条件 老师的name 是 yyh


select tec.name teacher,stu.name student from
tec inner join s_t on tec.id = s_t.t_id
inner join stu on s_t.s_id = stu.id
where tec.name = "egon" ;

子查询
什么是子查询:将上一次查询的结果 作为本次查询的原始数据(或是查询条件)
也就是嵌套查询 这中嵌套的语法一班不让写,不允许使用,

猜你喜欢

转载自www.cnblogs.com/1832921tongjieducn/p/11128910.html