这是一个子查询还是一个内连接
is this a subquery or just an inner join
我正在研究子查询的概念,下面是从维基百科中提取的一个查询https://en.wikipedia.org/wiki/Correlated_subquery
SELECT employees.employee_number, employees.name
FROM employees INNER JOIN
(SELECT department, AVG(salary) AS department_average
FROM employees
GROUP BY department) AS temp ON employees.department = temp.department
WHERE employees.salary > temp.department_average;
sql 是相关子查询的重写版本,如下所示
SELECT
employee_number,
name,
(SELECT AVG(salary)
FROM employees
WHERE department = emp.department) AS department_average
FROM employees AS emp;
现在我的问题是:
重写版本中的 sql 是子查询吗?我对此很困惑
INNER JOIN
(SELECT department, AVG(salary) AS department_average
FROM employees
GROUP BY department) AS temp ON employees.department = temp.department
WHERE employees.salary > temp.department_average;
欢迎使用 Whosebug。这肯定令人困惑,所以我会通过使用两个不同的 table 并且不使用 table 别名来简化它。
我会说,如果它在 FROM
子句中,则称为连接:
SELECT employee_id, department_name
FROM employees JOIN departments USING (department_id);
如果在WHERE
子句中,则称为子查询:
SELECT employee_id
FROM employees
WHERE employee_id = (
SELECT manager_id
FROM departments
WHERE employees.employee_id = departments.manager_id);
如果它在 SELECT
子句中,则称为 标量 子查询(感谢@Matthew McPeak):
SELECT employee_id,
(SELECT department_name
FROM departments
WHERE departments.department_id = employees.department_id)
FROM employees;
不完全是。等价于 left join
。相关版本保留 employees
table 中的所有行,即使没有匹配项也是如此。 inner join
要求匹配。
一般来说,执行计划不会完全相同,因为 SQL 引擎事先不知道所有行是否匹配。
加上过滤条件,两个版本是等价的。请注意,相关版本的过滤器需要子查询或 CTE,因为 where
子句不识别列别名。
我正在研究子查询的概念,下面是从维基百科中提取的一个查询https://en.wikipedia.org/wiki/Correlated_subquery
SELECT employees.employee_number, employees.name
FROM employees INNER JOIN
(SELECT department, AVG(salary) AS department_average
FROM employees
GROUP BY department) AS temp ON employees.department = temp.department
WHERE employees.salary > temp.department_average;
sql 是相关子查询的重写版本,如下所示
SELECT
employee_number,
name,
(SELECT AVG(salary)
FROM employees
WHERE department = emp.department) AS department_average
FROM employees AS emp;
现在我的问题是: 重写版本中的 sql 是子查询吗?我对此很困惑
INNER JOIN
(SELECT department, AVG(salary) AS department_average
FROM employees
GROUP BY department) AS temp ON employees.department = temp.department
WHERE employees.salary > temp.department_average;
欢迎使用 Whosebug。这肯定令人困惑,所以我会通过使用两个不同的 table 并且不使用 table 别名来简化它。
我会说,如果它在 FROM
子句中,则称为连接:
SELECT employee_id, department_name
FROM employees JOIN departments USING (department_id);
如果在WHERE
子句中,则称为子查询:
SELECT employee_id
FROM employees
WHERE employee_id = (
SELECT manager_id
FROM departments
WHERE employees.employee_id = departments.manager_id);
如果它在 SELECT
子句中,则称为 标量 子查询(感谢@Matthew McPeak):
SELECT employee_id,
(SELECT department_name
FROM departments
WHERE departments.department_id = employees.department_id)
FROM employees;
不完全是。等价于 left join
。相关版本保留 employees
table 中的所有行,即使没有匹配项也是如此。 inner join
要求匹配。
一般来说,执行计划不会完全相同,因为 SQL 引擎事先不知道所有行是否匹配。
加上过滤条件,两个版本是等价的。请注意,相关版本的过滤器需要子查询或 CTE,因为 where
子句不识别列别名。