- 查询每个部门的信息加部门的人数
SELECT * ,
(SELECT COUNT(1) FROM employees WHERE employees.department_id = departments.department_id)
FROM departments; - 查询每个部门的平均工资的工资等级
SELECT department_id,department_name,a , j.grade_level
FROM (
SELECT e.department_id ,d.department_name, AVG(salary) a
FROM employees e
LEFT JOIN departments d
ON e.department_id=d.department_id
GROUP BY e.department_id
) tmp
INNER JOIN job_grades j
ON tmp.a BETWEEN j.lowest_sal AND j.highest_sal; - 标量子查询:查询工资最少的员工信息
SELECT *
FROM employees
WHERE salary = (
SELECT MIN(salary)
FROM employees
); - 列子查询:查询location_id为1400或1500或2700的部门中的所有员工姓名
SELECT last_name
FROM employees
WHERE department_id IN (
SELECT department_id
FROM departments
WHERE location_id IN(1400,1500,2700)
); - 行子查询:查询编号最小并且工资最高的员工信息
#满足行子查询的条件笔记苛刻,所以用的不多
SELECT *
FROM employees
WHERE (employee_id,salary) = (
SELECT MIN(employee_id),MAX(salary)
FROM employees
);
(4)子查询在EXISTS后面(相关子查询)
EXISTS(SELECT 语句):有记录,则为1,无记录,则为0
相关子查询是先执行外查询,在由EXISTS过滤; 都能用IN代替 - 查询有员工的部门名
SELECT department_name
FROM departments d
WHERE EXISTS(
SELECT * FROM employees e WHERE e.department_id = d.department_id
);
#用IN代替
SELECT department_name
FROM departments d
WHERE d.department_id IN (
SELECT DISTINCT department_id
FROM employees
);
mysql学习
子查询
嵌套在其他语句的SELECT语句为子查询(内查询),外部的查询语句为主查询(外查询)
可分类为:
标量子查询(结果集只有一行一列)
列子查询(结果集多为一列多行)
IN、NOT IN:等于/不等于列表中的任意一个
ANY/SOME:子查询中某一个值满足就行
ALL:子查询中所以值都满足
行子查询(结果集多为一行多列)
表子查询(结果集有多行多列)
(1)子查询在SELECT后面
只支持标量子查询,如
查询每个部门的信息加部门的人数
SELECT * ,
(SELECT COUNT(1) FROM employees WHERE employees.department_id = departments.department_id)
FROM departments;
(2)子查询在FROM后面
支持表子查询,在一个SELECT查询后的表中查询新的内容,如:
查询每个部门的平均工资的工资等级
SELECT department_id,department_name,a , j.grade_level
FROM (
SELECT e.department_id ,d.department_name, AVG(salary) a
FROM employees e
LEFT JOIN departments d
ON e.department_id=d.department_id
GROUP BY e.department_id
) tmp
INNER JOIN job_grades j
ON tmp.a BETWEEN j.lowest_sal AND j.highest_sal;
(3)子查询在WHERE/HAVING后面
支持标量子查询、列子查询、行子查询