我目前正在学习SQL,我无法理解为什么这两个查询会返回不同数量的行(第一个返回53,而第二个返回69)。
SELECT d.department_name "dept_name",
j.job_title "job_title",
e.manager_id "manager_id",
MAX(e.salary) "max_salary",
SUM(e.salary) "sum_salary"
FROM employees e, jobs j, departments d
WHERE j.job_id = e.job_id AND
d.department_id(+) = e.department_id
GROUP BY GROUPING SETS( (d.department_name, j.job_title), (j.job_title,e.manager_id), ());
第二个:
SELECT d.department_name AS "dept_name",
j.job_title AS "job_title",
e.manager_id AS "manager_id",
MAX(e.salary) AS "max_salary",
SUM(e.salary) AS "sum_salary"
FROM employees e
INNER JOIN jobs j ON j.job_id = e.job_id
RIGHT OUTER JOIN departments d ON d.department_id = e.department_id
GROUP BY GROUPING SETS( (d.department_name, j.job_title), (j.job_title,e.manager_id), ());
感谢您的帮助!
答案 0 :(得分:0)
在旧式连接语法
FROM employees e, departments d
WHERE d.department_id(+) = e.department_id
是左连接,等于:
FROM employees e
LEFT JOIN departments d ON d.department_id = e.department_id
对于这些查询,两个工作完全相同,您还应该在第二个查询中将RIGHT JOIN更改为LEFT JOIN,或者将d.department_id(+)= e.department_id更改为d.department_id = e.department_id(+)in第一个。
答案 1 :(得分:0)
您的查询不同,因为在第一个外部联接表部门,而在第二个外部联接作业和员工。 (这就是为什么我不喜欢右外连接。我觉得它们不太可读。)你带员工,加入工作然后通过RIGHT OUTER JOIN你说:并且无论如何都给我所有的部门,所以给我为工作和员工提供额外的(外部联合记录)。第二个陈述等于:
SELECT d.department_name AS "dept_name",
j.job_title AS "job_title",
e.manager_id AS "manager_id",
MAX(e.salary) AS "max_salary",
SUM(e.salary) AS "sum_salary"
FROM departments d
LEFT OUTER JOIN employees e ON e.department_id = d.department_id
LEFT OUTER JOIN jobs j ON j.job_id = e.job_id
GROUP BY GROUPING SETS( (d.department_name, j.job_title), (j.job_title,e.manager_id), ());
在旧的Oracle语法中,您会写:
SELECT d.department_name "dept_name",
j.job_title "job_title",
e.manager_id "manager_id",
MAX(e.salary) "max_salary",
SUM(e.salary) "sum_salary"
FROM employees e, jobs j, departments d
WHERE e.department_id(+) = d.department_id
AND j.job_id(+) = e.job_id;