题目:查找所有员工的last_name和first_name以及对应的dept_name,也包括暂时没有分配部门的员工

方法1:先内连接departments表和dept_emp表形成新表b,再左连接employees表和b表
SELECT e.last_name, e.first_name, b.dept_name
FROM employees AS e
LEFT JOIN (SELECT *
FROM departments AS d
INNER JOIN dept_emp AS de
ON d.dept_no=de.dept_no
) AS b
ON e.emp_no=b.emp_no;

方法2:两次LEFT JOIN嵌套
SELECT last_name, first_name, dept_name
FROM (SELECT *
FROM employees
LEFT JOIN dept_emp
ON employees.emp_no=dept_emp.emp_no
) AS a
LEFT JOIN departments
ON a.dept_no=departments.dept_no;

SELECT em.last_name, em.first_name, dp.dept_name
FROM (employees AS em
LEFT JOIN dept_emp AS de
ON em.emp_no = de.emp_no)
LEFT JOIN departments AS dp
ON de.dept_no = dp.dept_no
注意:方法2中的2种子方法,主表是不同的。子方法1必须用AS a进行重命名,而且外面不能引用主表a中的连接子表employees或dept_emp。而子方法2的外面则可以引用主表中的连接子表。

方法3:两次LEFT JOIN连接
SELECT last_name, first_name, dept_name
FROM employees
LEFT JOIN dept_emp ON employees.emp_no=dept_emp.emp_no
LEFT JOIN departments ON dept_emp.dept_no=departments.dept_no;