sql cookbook 第三章 操作多個表 記

2021-08-22 00:02:22 字數 3088 閱讀 3968

3.4 從乙個表中查詢另乙個沒有值

問題:要從表dept中查詢在表emp中不存在資料的所有部門

1.沒有deptno為null時:

select deptno from dept where deptno  not in (select deptno from emp);
2.當emp表中有deptno為null時:

錯的:

select  deptno from dept where deptno  not in (select deptno from emp);
結果: null    

原因:in 和not in 本質是or運算

select  false or null;
null

select  true  or null;
注意:or運算中 ture or null ture  false or null null

解決:解決與not in 和null有關的問題,可以使用 not exists和相關子查詢。

select deptno from dept where not exists (select null from emp where emp.deptno=dept.deptno);
等價

select d.deptno from dept d where not exists (select 1 from new_dept e where d.deptno=e.deptno);
3.7 檢測兩個表中是否有相同的資料

問題:知道兩個表或檢視中是否有相同的資料(基數和值)

);在檢視v中不在表emp中:

select * from

(select v.comm,v.deptno,v.empno,v.ename,v.hiredate,v.job,v.mgr,v.sal,count(*) cnt from v37 v group by v.comm,v.deptno,v.empno,v.ename,v.hiredate,v.job,v.mgr,v.sal)v

where not exists

(select null from

(select e.comm,e.deptno,e.empno,e.ename,e.hiredate,e.job,e.mgr,e.sal,count(*) cnt from emp e group by e.comm,e.deptno,e.empno,e.ename,e.hiredate,e.job,e.mgr,e.sal )e

where e.comm=v.comm and e.deptno=v.deptno and e.empno=v.empno and e.ename=v.ename and e.hiredate=v.hiredate and e.job=v.job and e.mgr=v.mgr and e.sal=v.sal and v.cnt=e.cnt

);

v37中有2條資料ename='ward'的資料,而emp只有一條。通過count(*) cnt 選出來了,多個那條v37的資料。

SQLCookBook第三章學習日記9

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

SQLCookBook第三章學習日記10

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

第三章 堆疊

1.基礎知識 堆疊可以實現很多的應用,遞迴的問題轉化成非遞迴形式,在本質上也是堆疊的問題.它是一種 filo 操作的資料結構,一般也有兩種儲存方式 陣列跟鍊錶實現形式,這裡我給出了鍊錶形式的堆疊模板,裡面包括了基本的堆疊所有的操作,還有兩個比較著名的應用例子,時間倉促,精力比較有限,關於迷宮老鼠還沒...