SQL子查询

SQL的子查询

子查询的理解:查询 (内查询) 在主查询之前一次执行完成。子查询的结果被主查询(外查询)使用。

子查询要包含在括号内。 将子查询放在比较条件的右侧。 单行操作符对应单行子查询,多行操作符对应多行子查询。

单行子查询:只返回一行。使用单行比较操作符。

(单行比较操作符有: =, >, <> ,!= 等)

子查询的having字句:可以使用组函数

首先执行子查询。 向主查询中的having 子句返回结果。

多行子查询:返回多行语句,使用多行比较运算符。

(多行比较运算符:in any all)

in 等于返回结果中的任意一个

any 和返回结果的某一个值比较

all 和返回结果的所有值比较

背景:

–谁的工资比 Abel高?

–方法一:

–1)步骤一

select salary

from employees

where lower(last_name) = ‘abel’;

–2)步骤二

select last_name,salary

from employees

where salary > 11000;

–方法二:子查询 外查询

select last_name,salary

from employees

where salary > (

             select salary

            from employees

            where lower(last_name) = 'abel'

            );

–查询last_name 为’Chen’的员工的manager的信息

方法一 子查询

select employee_id,last_name,salary

from employees

where employee_id = (

                select manager_id

                from employees

                where last_name = 'Chen'

                );

方法二:

select mgr.employee_id,mgr.last_name,mgr.salary

from employees emp,employees mgr

where emp.manager_id = mgr.employee_id

and emp.last_name = ‘Chen’;

–43*. 查询平均工资最低的部门信息和该部门的平均工资

select d.*,(select avg(salary) from employees where department_id = d.department_id)

from departments d

where d.department_id = (

–2)找到最低的平均工资的部门id

select department_id

from employees

having avg(salary) = (

–1)查询出各个部门中的最低的平均工资

select min(avg(salary))

from employees

group by department_id)

group by department_id)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值