幫朋友優化個sql
今天朋友跟我說,有個sql消耗系統資源非常嚴重,看能不能幫忙優化下
sql本身不復雜,只是關聯了四五個表,有個表resultreport 3百多萬條資料庫,其他幾個表才幾千條几萬條記錄
Select A.Lineid,
A.Linecode,
A.Linename,
A.Man,
A.Time,
A.Way,
A.Desc,
D.Name,
Count(Distinct B.Hospid) as HospNum,
C.Lineman,
C.Carid,
Sum(decode(E.ReportType, '0', 1, Null)) As SumNomal,
Sum(decode(E.ReportType, '1', 1, Null)) As SumExecp,
Sum(decode(E.ReportType, '2', 1, Null)) As SumBacks,
Sum(decode(E.ReportType, '3', 1, Null)) As SumUnTest
from LineInfo A
join LineHosp B
ON A.Lineid = B.Lineid
left join Lineclass C
ON (A.Lineid = C.Lineid and C.Delidate = trunc(sysdate))
left join dUsers D
ON C.Lineman = D.Userid
left join resultreport E
on ((B.ServCycle like :ServCycle Or Trim(B.ServCycle) = '8') and
(B.Hospid = E.Hospid and E.State = '1'))
Group by A.Lineid,
A.Linecode,
A.Linename,
A.Man,
A.Time,
A.Way,
A.Desc,
D.Name,
C.Lineman,
C.Carid
Order by A.LineCode
cost代價為12萬多
把對resultreport 大表有查詢的條件,改成子查詢,然後再和b表關聯
改寫後的語句如下:
Select A.Lineid,
A.Linecode,
A.Linename,
A.Man,
A.Time,
A.Way,
A.Desc,
D.Name,
Count(Distinct B.Hospid) as HospNum,
C.Lineman,
C.Carid,
Sum(decode(E.ReportType, '0', 1, Null)) As SumNomal,
Sum(decode(E.ReportType, '1', 1, Null)) As SumExecp,
Sum(decode(E.ReportType, '2', 1, Null)) As SumBacks,
Sum(decode(E.ReportType, '3', 1, Null)) As SumUnTest
from LineInfo A,(select Lineid,Hospid from LineHosp
where ServCycle like :ServCycle Or Trim(ServCycle) = '8' ) B,Lineclass C,
dUsers D,(select ReportType,Hospid from resultreport where State = '1') E
where A.Lineid = B.Lineid
and A.Lineid = C.Lineid and C.Delidate = trunc(sysdate)
and C.Lineman = D.Userid
and B.Hospid = E.Hospid
Group by A.Lineid,
A.Linecode,
A.Linename,
A.Man,
A.Time,
A.Way,
A.Desc,
D.Name,
C.Lineman,
C.Carid
Order by A.LineCode;
cost代價變為1萬多,提高了10倍多
這個sql優化主要是重寫sql,對大表先查出需要的結果集再和其他小表關聯,這樣就提高查詢速度。
而原來大表和小表直接做關聯,掃描的資料更多,從而影響查詢速度。
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/7199859/viewspace-671882/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 8個SQL講解優化SQL優化
- MySQL 52個SQL效能優化策略SQL語句彙總MySql優化
- sql優化之邏輯優化SQL優化
- 資料庫優化 - SQL優化資料庫優化SQL
- SQL SERVER優化SQLServer優化
- SQL優化指南SQL優化
- Oracle效能優化-SQL優化(案例一)Oracle優化SQL
- Oracle效能優化-SQL優化(案例二)Oracle優化SQL
- Oracle效能優化-SQL優化(案例三)Oracle優化SQL
- Oracle效能優化-SQL優化(案例四)Oracle優化SQL
- SQL優化參考SQL優化
- sql優化專題SQL優化
- SQL語句優化SQL優化
- SQL效能優化技巧SQL優化
- MySQL-SQL優化MySql優化
- 慢Sql優化思路SQL優化
- Oracle SQL優化之sql tuning advisorOracleSQL優化
- SQL優化案例-使用with as優化Subquery Unnesting(七)SQL優化
- TiDB SQL調優案例之避免TiFlash幫倒忙TiDBSQL
- 資料庫優化SQL資料庫優化SQL
- MYSQL SQL語句優化MySql優化
- SQL優化之limit 1SQL優化MIT
- 優化sql查詢速度優化SQL
- (轉)SQL 優化原則SQL優化
- SQL優化的方法論SQL優化
- 史上最全SQL優化方案SQL優化
- MySQL SQL優化案例(一)MySql優化
- MySQL之SQL優化技巧MySql優化
- [20201224]sql優化困惑.txtSQL優化
- sql語句效能優化SQL優化
- SQL精華總結索引型別優化SQL優化事務大表優化思維導圖❤️SQL索引型別優化
- 厲害了!這個工具幫助你生成朋友圈轉發截圖
- SQL優化器探討(zt)SQL優化
- SQL優化案例-union代替or(九)SQL優化
- SQL優化之利用索引排序SQL優化索引排序
- 效能調優——SQL最佳化SQL
- 達夢SQL優化方法statSQL優化
- MySQL之SQL語句優化MySql優化
- Mysql慢SQL分析及優化MySql優化