tag union 條件
題目
查找所有員工的last_name和first_name以及對(duì)應(yīng)部門編號(hào)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));
輸入描述:
無(wú)
輸出描述:
image.png
思路
這道題是對(duì)只查詢已經(jīng)分配部門員工的拓展,又加入了另外一個(gè)還沒有分配員工的展示,那這樣就很容易想起來(lái),我能不能將另外的數(shù)據(jù)和以前已經(jīng)查出來(lái)的數(shù)據(jù)合并起來(lái)作為新的數(shù)據(jù)集合呢?這樣就想起來(lái)了關(guān)鍵字union使用這個(gè)關(guān)鍵字你會(huì)發(fā)現(xiàn)是錯(cuò)的
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)
當(dāng)我將兩部分拆開來(lái)看查詢結(jié)果的時(shí)候出現(xiàn)了一個(gè)很讓我意外的結(jié)果集合,因?yàn)檫@里面竟然有重復(fù)的數(shù)據(jù)

再次查語(yǔ)法發(fā)現(xiàn)
union會(huì)剔除結(jié)果集中重復(fù)的數(shù)據(jù),但是還有一個(gè)關(guān)鍵字可以解決這個(gè)問(wèn)題就是union all這樣就得到了最終的結(jié)果集合
答案為
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)
結(jié)論
-
union會(huì)剔除重復(fù)數(shù)據(jù) -
union all只是將兩次的結(jié)果集合合并,并不會(huì)出現(xiàn)數(shù)據(jù)剔除
