SQLCookBook第三章學習日記10

2021-07-24 16:25:36 字數 2883 閱讀 9752

問題:

同時返回多個表中丟失的資料。要從表dept中返回emp不存在的行(所有沒有員工的部門)需要做外聯結。考慮下面的查詢。它返回表dept中的deptno和name欄位,以及每個部門中所有員工的姓名。(如果該某個部門有員工的話):

select d.deptno, d.dname, e.ename

from dept d left

outer

join emp e

on (d.deptno = 3.deptno)

最後一行operations部門,儘管該部門沒有員工,還是返回了這一行,因為表emp被外聯結到了表dept。現在,假設有乙個員工沒有部門,那麼如何得到在上述的結果集,並未該沒有部門的員工返回一行呢?換句話說,要在同乙個的查詢中國同時外聯接到表emp和dept。在建立新員工之前,開始可能會這麼做:

insert

into emp (empno,ename,job,mgr,hiredae,sal,comm,deptno)

select

1111,'yoda','jedi',null,hiredate,sal,comm,null

from emp

where ename = 'king'

select d.deptno,d.name,e.ename

from dept d right

outer

join emp e

on (d.deptno = e.deptno)

使用外聯結是想返回新建立的員工,但卻將原結果集中的operations部門丟掉了。最終的結果集螢微員工yoda和部門operations各返回一行。

解決方案:使用基於公共之的完全外聯結來返回這兩個表中丟失的資料。

db2,mysql,postgresql和sql server

顯示使用full outer join命令返回兩個表中丟失的行為以及所有匹配的行;

select d.deptno,d.name,e.ename

from dept d full

outer

join emp e

on (d.deptno = e.deptno)

或者,合併兩個不同外聯結的結果:

select d.deptno,d.dname,e.ename,

from dept d right outer jin emp e

on(d.deptno = e.deptno)

union

select d.deptno ,d.dname,e.ename

from dept d, emp e

on (d.deptno = e.deptno)

oracle

如果使用oracle9idatabase及以後的版本,上樹的兩種解決方案都可以使用,也可以使用oracle所持有的外聯結語法,在oracle9i database及其以前的版本中,只能應用此語法來解決上述問題。

select d.deptno, d.name, e.ename

from dept d, emp e

where d.deptno = e.deptno(+)

union

select d.deptno, d.dname, e.ename

from dept d, emp e

where d.deptno(+) = e.deptno

討論

完全外聯結就是所有的表的外聯結簡單的合併,想要知道完全外聯結的詳細內幕只需執行每個外聯結,然後合併結果集即可。下面的查詢返回表dept的所有行及表emp中與之匹配的行(如果有的話):

select d.deptno ,d.dname,e.ename

from dept d left oter join emp e

on (d.deptno = e.deptno)

下面的查詢返回表emp的所有行及表dept中與之匹配的行(如果有的話):

select d.deptno, d.dname, e.ename

from dept d right

outer jpin emp e

on (d.deptno = e.deptno)

這兩個查詢合併的結果就是最終的結果集。

問題:

null值永遠不會等於或不等於任何值,也包括null值自己,但是需要像計算真實值一樣計算可為空列的返回值。例如,需要在表emp中查出所有比「ward」提成(comm)低的員工,提成為null(空)的員工也應當包括在其中。

解決方案:

使用coalesce函式將null值轉換為乙個可以用來作為標準值進行比較的真實值:

select ename,comm

from emp

where coalesce(comm,0) < (

select comm from emp

where ename = 'ward'

)

討論:

coalesce函式從值列表中返回第乙個非null值。當遇到null值是將其替換為0,這樣就可以同ward的提成進行比較了,也可以將coalesce函式放置在select列表中:

select ename,comm,coalesce(comm ,0)

from emp

where coalesce(comm , 0) < (

select comm from emp where ename = 'ward'

)

SQLCookBook第三章學習日記9

問題 要返回在部門10中每個員工的姓名,以及部門的工作地點,下面的查詢達到的是錯誤資料 selelct e.ename,d.loc from emp e dept d where e.deptno 10解決方案 在from子句對錶進行連線來返回正確的結果集 select e.ename,d.loc ...

sql cookbook 第三章 操作多個表 記

3.4 從乙個表中查詢另乙個沒有值 問題 要從表dept中查詢在表emp中不存在資料的所有部門 1.沒有deptno為null時 select deptno from dept where deptno not in select deptno from emp 2.當emp表中有deptno為nu...

第三章 Data語意學

1 關於data member的繫結 對於memner function的本體分析,會直到整個class的宣告都出現了才才開始。因此乙個inline member function軀體內的乙個data member的繫結操作,會在整個class宣告之後才發生。但是,對於member function...