MySQL-sql99-子查询-列子查询、行子查询
列子查询(多行子查询)
案例:返回location_id是1400或1700的部门中所有员工姓名
# ①查询location_id是1400或1700的部门编号
SELECT `department_id`
FROM `departments`
WHERE `location_id` IN(1400,1700);
是1列多行
满足列子查询
# ②查询员工姓名,要求部门号是①列表中的某一个
SELECT `last_name`
FROM `employees`
WHERE `department_id` IN (
SELECT `department_id`
FROM `departments`
WHERE `location_id` IN(1400,1700)
);
案例:返回其他工种中比job_id为'IT_PROG'工种任一工资低的员工的员工号、姓名、job_id以及salary
# ①查询job_id为'IT_PROG'部门任一工资
SELECT DISTINCT `salary`
FROM `employees`
WHERE `job_id`='IT_PROG';
# ②查询员工号、姓名、job_id以及salary salary<any(①)
SELECT `last_name`,`employee_id`,`job_id`,`salary`
FROM `employees`
WHERE `salary`<ANY(
SELECT DISTINCT `salary`
FROM `employees`
WHERE `job_id`='IT_PROG')
AND job_id<>'IT_PROG';
也可以用max()来代替any()
# ①查询job_id为'IT_PROG'部门任一工资
SELECT DISTINCT `salary`
FROM `employees`
WHERE `job_id`='IT_PROG';
# ②查询员工号、姓名、job_id以及salary salary<any(①)
SELECT `last_name`,`employee_id`,`job_id`,`salary`
FROM `employees`
WHERE `salary`<(
SELECT MAX(`salary`)
FROM `employees`
WHERE `job_id`='IT_PROG')
AND job_id<>'IT_PROG';
结果还是一样的
返回其它部门中比job_id为'IT_PROG'部门所有工资部低的员工的员工号、姓名、job_id 以及salary
#返回其它部门中比job_id为'IT_PROG'部门所有工资部低的员工的员工号、姓名、job_id 以及salary
#① 先查询job_id为'IT_PROG'部门的所有工资
SELECT DISTINCT `salary`
FROM `employees`
WHERE `job_id`='IT_PROG';
#② 查询员工的员工号、姓名、job_id 以及salary,并且工资比①中都低
SELECT `employee_id`,`last_name`,`job_id`,`salary`
FROM `employees`
WHERE salary <ALL(
SELECT DISTINCT `salary`
FROM `employees`
WHERE `job_id`='IT_PROG'
) AND `job_id`<>'IT_PROG';
或者换成min(salary)
#① 先查询job_id为'IT_PROG'部门的所有工资
SELECT DISTINCT `salary`
FROM `employees`
WHERE `job_id`='IT_PROG';
#② 查询员工的员工号、姓名、job_id 以及salary,并且工资比①中都低
SELECT `employee_id`,`last_name`,`job_id`,`salary`
FROM `employees`
WHERE salary <(
SELECT MIN(`salary`)
FROM `employees`
WHERE `job_id`='IT_PROG'
) AND `job_id`<>'IT_PROG';
同样的效果
其中第一个案例
案例:返回location_id是1400或1700的部门中所有员工姓名
# 案例:返回location_id是1400或1700的部门中所有员工姓名
SELECT `last_name`
FROM `employees`
WHERE `department_id` in (
SELECT `department_id`
FROM `departments`
WHERE `location_id` IN(1400,1700)
);
代码是上面的 也可以用any代替in
# 案例:返回location_id是1400或1700的部门中所有员工姓名
SELECT `last_name`
FROM `employees`
WHERE `department_id` =ANY (
SELECT `department_id`
FROM `departments`
WHERE `location_id` IN(1400,1700)
);
效果是一样的
行子查询(结果集一行多列或多行多列)
引入
案例:查询员工编号最小并且工资最高的员工信息
#①查询最小的员工编号
SELECT MIN(`employee_id`)
FROM `employees`;
#查询最高工资
SELECT MAX(`salary`)
FROM `employees`;
#查询员工信息
SELECT *
FROM `employees`
WHERE `employee_id`=(
SELECT MIN(`employee_id`)
FROM `employees`
)
AND `salary`=(
SELECT MAX(`salary`)
FROM `employees`
)
行子查询是有条件的 当筛选条件全部都是等于的情况时候 用行子查询
select *
from `employees`
where (`employee_id`,`salary`)=
(
select min(`employee_id`),max(`salary`)
from `employees`
);
转载请注明出处,欢迎讨论和交流!