查找所有员工的last_name和first_name以及对应部门编号dept_no,也包括展示没有分配具体部门的员工
tagunion条件
题目
查找所有员工的last_name和first_name以及对应部门编号dept_no,也包括展示没有分配具体部门的员工
CREATE TABLEdept_emp(
emp_noint(11) NOT NULL,
dept_nochar(4) NOT NULL,
from_datedate NOT NULL,
to_datedate NOT NULL,
PRIMARY KEY (emp_no,dept_no));
CREATE TABLEemployees(
emp_noint(11) NOT NULL,
birth_datedate NOT NULL,
first_namevarchar(14) NOT NULL,
last_namevarchar(16) NOT NULL,
genderchar(1) NOT NULL,
hire_datedate NOT NULL,
PRIMARY KEY (emp_no));
输入描述:
无
输出描述:
image.png
思路
这道题是对只查询已经分配部门员工的拓展,又加入了另外一个还没有分配员工的展示,那这样就很容易想起来,我能不能将另外的数据和以前已经查出来的数据合并起来作为新的数据集合呢?这样就想起来了关键字union使用这个关键字你会发现是错的
select last_name,first_name,dept_no from employees,dept_emp where employees.emp_no = dept_emp.emp_no union select last_name,first_name,'None' from employees where employees.emp_no not in (select emp_no from dept_emp)
当我将两部分拆开来看查询结果的时候出现了一个很让我意外的结果集合,因为这里面竟然有重复的数据
image.png
再次查语法发现union会剔除结果集中重复的数据,但是还有一个关键字可以解决这个问题就是union all这样就得到了最终的结果集合
答案为
select last_name,first_name,dept_no from employees,dept_emp where employees.emp_no = dept_emp.emp_no union all select last_name,first_name,'None' from employees where employees.emp_no not in (select emp_no from dept_emp)
结论
- union会剔除重复数据
- union all只是将两次的结果集合合并,并不会出现数据剔除