8--mysql DQL--子查询

含义

出现在其他语句中的select语句,称为子查询或内查询,
外部的查询语句,称为主查询或外查询。
分类:
1 按子查询出现的位置:
select 后面:仅仅支持标量子查询
from后面:支持表子查询 创建临时表
where 或 having后面:支持 标量子查询,列子查询,行子查询
exists后面(相关子查询)
2 按结果集的行列数不同:
标量子查询(结果集只有一行一列)
列子查询(结果集只有一列多行)
行自查询(结果集只有一行多列)
表子查询(结果集一般为多行多列)
特点:
子查询放在小括号内
子查询一般放在条件的额右侧
标量子查询,一般搭配着单行操作符使用 > < >= <= <>
列子查询,一般搭配置多行操作符使用 in, any/some , all

标量子查询:

谁的工资比 Abel 高
SELECT last_name, salary FROM employees 
WHERE salary > (
 SELECT salary  FROM  employees WHERE last_name = 'Abel'
 ) ;

返回job_id与141号员工相同,salary比143号员工多的员工信命,job_id,工资
SELECT last_name,job_id,salary 
FROM employees e
WHERE e.job_id=(SELECT job_id FROM employees WHERE employee_id=141)
AND e.`salary`>(SELECT salary FROM employees WHERE employee_id=143);

select 后面:查询每个部门的员工个数
SELECT d.*,
(SELECT COUNT(*) FROM employees e WHERE e.department_id=d.department_id) 个数
FROM departments d;

查询员工号等与102的部门名
SELECT department_name FROM departments d WHERE d.`department_id`=
(SELECT department_id FROM employees e WHERE e.`employee_id`=102);


列子查询(多行子查询)

返回location_id是14001700的部门中的所有员工姓名
SELECT e.last_name FROM employees e WHERE e.`department_id` IN
(SELECT DISTINCT department_id FROM departments d WHERE d.`location_id` IN (1400,1700));

其它案例

查询各个部门中工资比本部门平均工资高的员工的员工编号,姓名和工资
SELECT e.`employee_id`,e.`last_name`,e.`salary`
FROM employees e
INNER JOIN  
(SELECT AVG(salary) ss,e.`department_id` id FROM employees e
GROUP BY e.`department_id`) tempresult  #创建临时表
ON e.`department_id`=tempresult.id
WHERE e.`salary`>tempresult.ss;

查询在部门的location_id 为1700的部门工作的员工的员工号
实现1:创建临时表
SELECT e.`employee_id` FROM employees e
INNER JOIN 
(SELECT DISTINCT d.department_id FROM departments d
WHERE d.`location_id`=1700) temp
ON e.`department_id`=temp.department_id

实现2:使用any关键字
SELECT e.`employee_id` FROM employees e
WHERE e.`department_id`=ANY(
SELECT DISTINCT d.department_id FROM departments d
WHERE d.`location_id`=1700
);

实现3:使用  in
SELECT e.`employee_id` FROM employees e
WHERE e.`department_id` IN(
SELECT DISTINCT d.department_id FROM departments d
WHERE d.`location_id`=1700
);

查询管理者是King的员工的姓名,工资
第一步:查出姓名为King的员工编号
SELECT employee_id FROM employees WHERE last_name='King'
第二部:查出员工的管理者是一中的结果
SELECT e.last_name,e.salary FROM employees e
WHERE e.`manager_id` IN(SELECT employee_id FROM employees WHERE last_name='King');

你可能感兴趣的:(Mysql)