sql語句優化

2021-08-30 12:54:04 字數 1330 閱讀 3444

今天在優化乙個先人留下的sql語句時,發現有兩個問題。在這些問題被解決後,sql語句執行效率有了很大的提高。

首先介紹一下情況。

資料庫是oracle。

我們使用的資料表有40+的字段。大概有4-5w條資料。

我們需要獲取乙個主管所負責的所有資料。

元sql是這樣的:

select * from opened_ar where  

customerid in

(select distinct customerid from opened_ar where

( sec not like 'sa%' and sec not like 'kr%')

and amt > 0 and sh_of_sales=&sh and ich != &sh

)and bill_date < to_date('2010-3-1','yyyy-mm-dd')

and (sec not like 'sa%' and sec not like 'kr%') and amt > 0

order by customername1 desc,bill_date desc

在嘗試抓取乙個只有49條記錄的結果集時,竟然用時630s。崩潰了。

發現有兩個問題:

使用了in關鍵字。雖然in對應的()內也只有幾條資料,但是同樣會影響速度。應該使用exists

bill_date無法過濾掉大量的資料,應該放在最接近where的地方。可以過濾大量資料的條件放在距離where最遠的地方。(因為sql語句是從下往上執行的)

最終的sql語句改為這樣:

select * from opened_ar o1 where  

bill_date < to_date('2010-3-1','yyyy-mm-dd')

and (sec not like 'sa%' and sec not like 'kr%') and amt > 0

and exists

(select customerid from opened_ar o2 where ( o2.sec not like 'sa%' and o2.sec not like 'kr%') and o2.amt > 0 and o2.sh_of_sales=&sh and o2.ich != &sh and o2.customerid = o1.customerid

)order by customername1 desc,bill_date desc

修改後,原來630s的時間,竟然縮減為不到一秒鐘。非常好。以上是我的小修改。或許還有更好的方法。但這樣已經可以達到我目前的需求了。

SQL 語句優化 OR 語句優化案例

從上海來到溫州,看了前幾天監控的sql語句和資料變化,發現有一條語句的io次數很大,達到了150萬次io,而兩個表的資料也就不到20萬,為何有如此多的io次數,下面是執行語句 select ws.nodeid,wi.laststepid,wi.curstepid from workflowinfo ...

sql語句優化!

1.不要使用in操作符,這樣資料庫會進行全表掃瞄,推薦方案 在業務密集的sql當中盡量不採用in操作符 a 改為 a 4.is null 或is not null操作 判斷字段是否為空 5.及 操作符 大於或小於操作符 大於或小於操作符一般情況下是不用調整的,因為它有索引就會採用索引查詢,但有的情況...

SQL語句優化

explain sql 反饋sql語句執行資訊 1 優化 select min id as nid,uid pmzongfen updatetime picid gg from qd mouldu qd sell limit 1 select uid pmzongfen updatetime pic...