Mysql学习记录(三)多表查询

分类

内连接

隐式内连接: 使用where条件消除无用数据
-- 查询所有员工信息和对应的部门信息
select * from emp,dept where emp.dept_id = dept.id;
显式内连接
  • 语法:select 字段 from 表名 inner join 另一表名 on 条件语句
-- 查询所有员工信息和对应的部门信息
select * from emp inner join dept on emp.dept_id = dept.id;
-- 不加inner也可以
select * from emp join dept on emp.dept_id = dept.id;

外连接

左外连接
-- 查询所有员工信息和对应的部门信息,如果没有部门信息显示为NULL
select * from emp left outer join dept on emp.dept_id = dept.id;
-- 不加outer也可以
select * from emp left join dept on emp.dept_id = dept.id;
右外连接
-- 查询所有员工信息和对应的部门信息,如果没有部门信息则不显示
select * from emp right outer join dept on emp.dept_id = dept.id;
-- 不加outer也可以
select * from emp right join dept on emp.dept_id = dept.id;

子查询

套娃查询

子查询的结果是单行单列的

-- 查询员工当中工资最高的员工信息
select * from emp where salary = (select max(salary) from emp);
-- 查询员工当中小于平均工资的人
select * from emp where salary < (select avg(salary) from emp));

子查询的结果是多行单列的

子查询可以作为条件, 使用运算符in来判断

--查询“财务部”和“市场部所有的员工信息”
	-- 首先查出财务部和市场部在dept表中的id
select id from dept where name = '财务部' or name = '市场部';
	-- 然后根据dept_id 查出对应的员工信息
select * from emp where dept_id = 2 or dept = 3;
select * from emp where dept_id in (2,3);
-- 合并成一条
select 
	* 
from 
	emp 
where 
	dept_id in (select id from dept where name = '财务部' or name = '市场部');

子查询的结果是多行多列的

--查询员工入职日期是2011-11-11日之后的员工信息和部门信息
--首先查询员工入职日期是2011-11-11日之后的员工信息
select * from emp where join_date > '2011-11-11'
-- 然后将这条SQL查询出来的结果作为一张虚拟表
select 
	* 
from 
	dept t1 , (select * from emp where join_date > '2011-11-11') t2 
where 
	t1.id = t2.dept.id
-- 也可以使用普通内连接的方式查询
select 
	* 
from 
	emp , dept 
where 
	emp.dept_id = dept.id 
and 
	emp.join_date > '2011-11-11'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值