MySql-多表查询

多表查询

数据准备

#不存在外键关联的两张表
#一张表示员工表 
#存在一些不正确的部门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,"行政");

笛卡尔积查询

是两张表相乘的结果,若左边有m条 右边有n条 查询结果为m*n条; 往往包含大量错误数据

 select * from dept,emp;  

内连接查询

查询出两张表都有匹配关系的记录

select * from dept,emp where dept.id=emp.dept_id;    
select * from dept inner join emp on dept.id=emp.dept_id;
# 在多表查询中要筛选的是两边的关系,on用于过滤关联关系。而where单独做条件过滤,这样sql看起来可以更清晰明确,当然where依然可以代替on,inner可以省略

左连接查询

以左边的表为基准全部显示出来,右表中仅显示匹配成功的记录

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

右连接查询

以右边的表为基准全部显示出来,左表中仅显示匹配成功的记录

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

全外连接

无论是否匹配成功,两边表中的记录都要全部显示。mysql中可以使用合并查询结果 在所有语句最后写分号

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

union 只能用于字段数量相同的两个表 会自动去除重复的记录

union all 则保留所有记录

子查询

将表的查询结果作为另一个查询语句的条件(内层)

in 关键字子查询

select name from dept where id in  (select dept_id from emp group by dept_id having avg(age)

exists 关键字子查询

exists 后跟子查询,子查询有结果是为True,外层执行;没有结果时为False,外层不执行

select *from emp where exists (select *from emp where salary > 1000);

多表查询练习https://www.cnblogs.com/863652104kai/p/11253605.html

原文地址:https://www.cnblogs.com/863652104kai/p/11253608.html