查找所有員工的last_name和first_name以及對(duì)應(yīng)部門編號(hào)dept_no,也包括展示沒有分配具體部門的員工

tag union 條件

題目

查找所有員工的last_name和first_name以及對(duì)應(yīng)部門編號(hào)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));

輸入描述:
無(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ù)

image.png

再次查語(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é)論

  1. union 會(huì)剔除重復(fù)數(shù)據(jù)
  2. union all 只是將兩次的結(jié)果集合合并,并不會(huì)出現(xiàn)數(shù)據(jù)剔除

參考

SQL UNION 子句

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容