描述
有一個員工表employees簡況如下:
有一個部門表departments表簡況如下:
有一個茁肠,部門員工關(guān)系表dept_emp簡況如下:
請你查找所有員工的last_name和first_name以及對應(yīng)的dept_name,也包括暫時沒有分配部門的員工缩举,以上例子輸出如下:
示例1
輸入:
drop table if exists? `departments` ;
drop table if exists? `dept_emp` ;
drop table if exists? `employees` ;
CREATE TABLE `departments` (
`dept_no` char(4) NOT NULL,
`dept_name` varchar(40) NOT NULL,
PRIMARY KEY (`dept_no`));
CREATE TABLE `dept_emp` (
`emp_no` int(11) NOT NULL,
`dept_no` char(4) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,
PRIMARY KEY (`emp_no`,`dept_no`));
CREATE TABLE `employees` (
`emp_no` int(11) NOT NULL,
`birth_date` date NOT NULL,
`first_name` varchar(14) NOT NULL,
`last_name` varchar(16) NOT NULL,
`gender` char(1) NOT NULL,
`hire_date` date NOT NULL,
PRIMARY KEY (`emp_no`));
INSERT INTO departments VALUES('d001','Marketing');
INSERT INTO departments VALUES('d002','Finance');
INSERT INTO departments VALUES('d003','Human Resources');
INSERT INTO dept_emp VALUES(10001,'d001','1986-06-26','9999-01-01');
INSERT INTO dept_emp VALUES(10002,'d001','1996-08-03','9999-01-01');
INSERT INTO dept_emp VALUES(10003,'d002','1990-08-05','9999-01-01');
INSERT INTO employees VALUES(10001,'1953-09-02','Georgi','Facello','M','1986-06-26');
INSERT INTO employees VALUES(10002,'1964-06-02','Bezalel','Simmel','F','1985-11-21');
INSERT INTO employees VALUES(10003,'1959-12-03','Parto','Bamford','M','1986-08-28');
INSERT INTO employees VALUES(10004,'1954-05-01','Chirstian','Koblick','M','1986-12-01');
我的錯誤寫法:
```
select e.last_name,e.first_name,t1.dept_name
from employees e left join
(select * from dept_emp de
left join departments d
on de.dept_no=d.dept_no) as t1
on e.emp_no = t1.emp_no
#報錯duplicate colunm name 'dept_no'
#第3列的 *垦梆,*代表表中所有列都要展示,dept_emp和departments表里都有dept_no字段
#因為在做合并的時候兩張表都有dept_no,必須指定好名字
```
正確寫法:
```
select e.last_name,e.first_name,t1.dept_name
from employees e left join
(select de.emp_no,d.dept_no,d.dept_name from dept_emp de
left join departments d
on de.dept_no=d.dept_no) as t1
on e.emp_no = t1.emp_no
```
其他解法:
```
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
```
reference:
https://www.nowcoder.com/practice/5a7975fabe1146329cee4f670c27ad55?tpId=82&tags=&title=&difficulty=0&judgeStatus=0&rp=1