Mysql的子查询

一.标量子查询

子查询返回单个数值(数字,字符串,日期等),最简单的形式。

举例:如一张员工表一张部门表,通过部门ID关联,查出销售部的员工信息。

首先可以拆分成两部分,先获取部门ID,再查找对应的员工信息。

select id from dept where dept_name=’销售部';//结果id=4

select  * from emp where  dept_id=4;

然后我们来看子查询,将上一条语句直接插入下一条。

select  * from emp where  dept_id=(select id from dept where dept_name=’销售部’);

这就是一个简单标量子查询

二.列子查询

子查询返回的值是一列的属性(可以是多行),常用in ,not in,some和any(两者基本用法一致),all等连接。

举例:查询部门为销售部和市场部的员工信息。

select * from emp where dept_id in (select id from dept where name = '销售部' or name = '市场部');

查询比财务部所有员工工资都高的员工信息(聚合函数不能在where后面使用,换成group by和having)。

select * from emp where salary >all (select salary from emp where dept_id=(select id from dept where name = '财务部‘));

查询比财务部任意员工工资都高的员工信息 

select * from emp where salary >any (select salary from emp where dept_id=(select id from dept where name = '财务部‘));

三.行子查询

子查询返回的数据是一行(可以是多列),常用=,<>,in,not in

举例:查询与liust薪资和领导相同的员工信息

select * from emp where (salary ,managerId)=(select salary ,managerId where name= 'liust');

四.表子查询

子查询返回的数据是一张表

举例:查询与liust或songyq薪资职位相同的员工信息。

select * from emp where (salary,job) in (select salary,job from emp where name='liust' or name = 'songyq');

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值