oracle多表查詢

2021-08-26 11:55:00 字數 2902 閱讀 1259

– 多表連線

– 1)內連線

– 2)外連線

– 3)自連線

select * from scott.emp; – 13

select * from scott.dept; – 7

– 笛卡爾集(了解)

– 主要忽略了乙個連線條件或者說乙個連線條件失效了

– 第一張表中的資料與第二張表中的所有資料(行)都有連線,造成資料的交集。

select * from scott.emp, scott.dept

where scott.emp.ename = 『smith』;

– 開發中,需要避免笛卡爾集

– 如果要避免的話,我們需要包含乙個有效連線條件的 where 子句。

– 內連線

– 兩個表(連線)中某一資料項相等的連線叫內連線。也叫等值連線。

– where tb_stu.clazz_id = tb_clazz.id

– 內連線的運算順序

– 1)參與的資料表(或連線)中的每列與其它資料表(或連線)的列匹配,會形成乙個臨時表。

– 2)將滿足資料項相等的記錄從臨時資料表中選擇出來。

select * from scott.dept, scott.emp

where scott.dept.deptno = scott.emp.deptno

and scott.emp.ename = 『smith』; – 20

– 使用別名

select * from scott.dept d, scott.emp e

where d.deptno = e.deptno

and e.ename = 『smith』;

– 查詢指定列

select d.deptno 部門編號, d.dname 部門名稱, e.sal 薪資

from scott.dept d, scott.emp e

where d.deptno = e.deptno

and e.ename = 『smith』;

select d.deptno 部門編號, d.dname 部門名稱, e.*

from scott.dept d, scott.emp e

where d.deptno = e.deptno

and e.ename = 『smith』;

– 內連線的標準寫法(了解)

– inner join 就是乙個逗號 ,

select * from scott.dept d inner join scott.emp e

on d.deptno = e.deptno

and e.ename = 『smith』; – 20

– 外連線(非等值連線)

– 用來查詢一張表在另一張中沒有關聯資料的資訊。

– 外連線的三種方式

– 1)左外連線 left outer join(重點)

– 2)右外連線 right outer join

– 2)全外連線 full outer join

select * from scott.emp; – 13

select * from scott.dept; – 7

– 等值連線:兩張表中都有的資料

select * from scott.dept d, scott.emp e

where d.deptno = e.deptno;

– 左外連線

– 技巧:如果是左外,就在右邊加 + 號。

– 左邊的表會展示出所有的資料,右邊表沒有對應的資料則顯示 null。

select * from scott.dept d, scott.emp e

where d.deptno = e.deptno(+);

– 左外的標準寫法

– 書寫的時候,需要注意:where 需要改為 on

select * from scott.dept d left outer join scott.emp e

on d.deptno = e.deptno;

– 右外連線

select * from scott.dept d, scott.emp e

where d.deptno(+) = e.deptno;

select * from scott.dept d right outer join scott.emp e

on d.deptno = e.deptno;

– 全外連線

select * from scott.dept d full outer join scott.emp e

on d.deptno = e.deptno;

– 自連線(重點)

– 在開發中使用比較廣泛

– 使用自連線的時候,相當於複製了乙個映象物件出來,並可以當做另外一張表來處理。

– 《與神對話》1,2,3

– 使用了自連線可以把一張表當做多張表來使用,獲取一些比較特殊的資料。

– 使用技巧:可以考慮把它當做外來鍵來玩。

select * from scott.emp;

– 乙個普通員工有自己的經理,經理也是乙個員工,經理也有自己的經理

– 查詢 smith 的員工編號,名稱,上級經理的編號,上級經理的名稱

– 建立乙個臨時表,資料來自 scott.emp

create table tb_temp as select * from scott.emp;

– 關鍵釐清物件之間的關係

select e1.empno, e1.ename, e1.mgr, e2.ename

from scott.emp e1, tb_temp e2

where e1.mgr = e2.empno

and e1.ename = 『smith』;

Oracle 多表查詢

sql 外連線 sql 按部門統計員工人數 部門號 部門名稱 人數 sql select d.deptno,d.dname,count e.empno 2 from dept d,emp e 3 where d.deptno e.deptno 4 group by d.deptno,d.dname ...

Oracle 多表查詢

等值和不等值連線查詢 為了避免笛卡爾集,可以在 where 加入有效的連線條件。oracle 連線多表查詢 在 where 子句中寫入連線條件。在表中有相同列時,在列名之前加上表名字首 select table1.column,table2.column from table1,table2 whe...

oracle 多表查詢

多表查詢 多表查詢,又稱表聯合查詢,即一條sql語句涉及到的表有多張,資料通過特定的連線進行聯合顯示.笛卡爾積 在數學中,兩個集合x和y的笛卡尓積 cartesian product 又稱直積,表示為x y.假設集合a 集合b 則兩個集合的笛卡爾積為。在資料庫中,如果直接查詢倆張表,那麼其查詢結果就...