sql错题 合并后选择字段问题

2021-08-08  本文已影响0人  yannanoo

描述

有一个员工表employees简况如下:

有一个部门表departments表简况如下:

有一个,部门员工关系表dept_emp简况如下:

请你查找所有员工的last_name和first_name以及对应的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

上一篇 下一篇

猜你喜欢

热点阅读