兩種優化查詢的方法

2021-07-23 11:43:24 字數 2272 閱讀 3816

兩種優化表查詢的方法:

1、表的查詢順序(針對多表查詢)

oracle的解析器按照從右到左的順序處理from子句中的表名,因此from子句中寫在最後的表(基礎表 driving table)將被最先處理。 在from子句中包含多個表的情況下,你必須選擇記錄條數最少的表作為基礎表。當oracle處理多個表時, 會運用排序及合併的方式連線它們。首先,掃瞄第乙個表(from子句中最後的那個表)並對記錄進行派序,然後掃瞄第二個表(from子句中最後第二個表),最後將所有從第二個表中檢索出的記錄與第乙個表中合適記錄進行合併。

例如:

表 tab1 16,384 條記錄

表 tab2 1 條記錄

選擇tab2作為基礎表 (最好的方法)

select

count(*) from tab1,tab2 執行時間0.96秒

選擇tab1作為基礎表 (不佳的方法)

select count(*) from tab2,tab1   執行時間26.09秒
如果有3個以上的表連線查詢, 那就需要選擇交叉表(intersection table)作為基礎表, 交叉表是指那個被其他表所引用的表。

例如: emp表描述了location表和category表的交集。

select * 

from location l,

category c,

emp e

where e.emp_no between 1000

and2000

and e.cat_no = c.cat_no

and e.locn = l.locn

將比下列sql更有效率

select * 

from emp e ,

location l ,

category c

where e.cat_no = c.cat_no

and e.locn = l.locn

and e.emp_no between 1000

and2000

2、不是用in

用exists替代in

在許多基於基礎表的查詢中,為了滿足乙個條件,往往需要對另乙個表進行聯接。在這種情況下, 使用exists(或not exists)通常將提高查詢的效率。

低效:

select * 

from emp (基礎表)

where empno > 0

and deptno in (select deptno

from dept

where loc = 『melb』)

高效:

select * 

from emp (基礎表)

where empno > 0

andexists (select 『x』

from dept

where dept.deptno = emp.deptno

and loc = 『melb』)

用not exists替代not in

在子查詢中,not in子句將執行乙個內部的排序和合併。 無論在哪種情況下,not in都是最低效的 (因為它對子查詢中的表執行了乙個全表遍歷)。 為了避免使用not in ,我們可以把它改寫成外連線(outer joins)或not exists。

例如:

select …

from emp

where dept_no not

in (select dept_no

from dept

where dept_cat=』a』);

為了提高效率,改寫為:

(方法一: 高效)

select ….

from emp a,dept b

where a.dept_no = b.dept(+)

and b.dept_no is

null

and b.dept_cat(+) = 『a』

(方法二: 最高效)

select ….

from emp e

where

notexists (select 『x』

from dept d

where d.dept_no = e.dept_no

and dept_cat = 『a』);

兩種查詢方法

1.問題 寫出兩種檢索演算法 在乙個排好序的陣列t 1 n 中查詢x,如果x在t中,輸出x在t的下標j 如果x不在t中,輸出j 0.按實驗模板編寫,分析 部分僅給出複雜度結果即可。2.解析 問題的理解和推導,可用電子版直接在此編寫,也可用紙筆推導,拍照嵌入本文件 1.順序查詢,最簡單最經典的思路,從...

兩種簡單的查詢方法

這兩種查詢方法是 順序查詢法,二分法查詢 順序查詢法 思想 簡單地說就是那那個要找的數挨個與陣列中的數比較 二分法查詢 首先二分法查詢要求要查詢的陣列中的數必須是經過排序的 思想 就是先找到陣列中中間的那個數與要查詢的數進行比較,如果中間的數大 中間的數小 就去取中間的數左邊 右邊 的那個陣列中的中...

兩種attach to process的方法

背景 今天在做keepalive的實驗,設法模擬keepalive不成功的場景,從而達到 the local tcp will keep sending keep alive packet in an interval of keepaliveinterval for tcpmaxdataretra...