MySQL中的嵌套查询,也称为子查询(Subquery),是指在一个查询语句中嵌入另一个查询语句。子查询可以出现在SELECT、FROM、WHERE和HAVING子句中。子查询的结果可以作为外部查询的条件或数据来源。
假设我们有两个表:employees
和 departments
,结构如下:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
department_id INT
);
CREATE TABLE departments (
id INT PRIMARY KEY,
name VARCHAR(100)
);
查询工资最高的员工姓名:
SELECT name
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);
查询每个部门的所有员工姓名:
SELECT d.name AS department_name, e.name AS employee_name
FROM departments d
JOIN employees e ON d.id = e.department_id;
查询同时属于两个部门的员工:
SELECT e.name
FROM employees e
WHERE (e.department_id, e.job_title) IN (
SELECT department_id, job_title
FROM employees
GROUP BY department_id, job_title
HAVING COUNT(*) > 1
);
查询所有部门的名称及其员工数量:
SELECT d.name AS department_name,
(SELECT COUNT(*) FROM employees e WHERE e.department_id = d.id) AS employee_count
FROM departments d;
原因:子查询可能会导致多次扫描表,尤其是在大数据量情况下。
解决方法:
假设我们要查询每个部门的平均工资:
-- 原始子查询
SELECT d.name AS department_name,
(SELECT AVG(salary) FROM employees e WHERE e.department_id = d.id) AS average_salary
FROM departments d;
优化后的查询:
SELECT d.name AS department_name,
AVG(e.salary) AS average_salary
FROM departments d
JOIN employees e ON d.id = e.department_id
GROUP BY d.id;
通过以上内容,希望你能对MySQL嵌套查询有更深入的了解,并能解决相关问题。
领取专属 10元无门槛券
手把手带您无忧上云