天天看點

轉 資料庫優化方法

索引:建立索引一般有以下兩個目的:維護被索引列的唯一性和提供快速通路表中資料的政策。95% 的資料庫能問題都可以采用索引技術得到解決。索引有助于提高檢索性能,但過多或不當的索引也會導緻系統低效。因為使用者在表中每加進一個索引,資料庫就要做更多的工作。過多的索引甚至會導緻索引碎片。 

緩存:hibernate,spring3有緩存子產品

分表:針對每個時間周期産生大量的資料,可以考慮采用一定的政策将資料存到多個資料表中。

分庫:就是将系統按照子產品相關的特征分布到不同的資料中,以提高系統整體負載能力。

sql優化:

 1.in 和 not in 也要慎用,因為in會使系統無法使用索引,而隻能直接搜尋表中的資料。如:

select id from t where num in(1,2,3)對于連續的數值,能用 between 就不要用 in 了:

select id from t where num between 1 and 3

2.當判斷真假是,如果帶and 或者 or :

(當存在 “where 條件1 and 條件2” 時,資料庫先執行右邊的語句)

and盡量把假的放到右邊(一個為假就為假)  or盡量把為真的放到右邊(一個為真就為真)

3.應盡量避免在 where 子句中對字段進行表達式操作,這将導緻引擎放棄使用索引而進行全表掃描。 如:

select * from t1 where f1/2=100 

應改為: 

select * from t1 where f1=100*2

select * from record where substring(card_no,1,4)=’5378’ 

select * from record where card_no like ‘5378%’

select member_number, first_name, last_name from members 

where datediff(yy,datofbirth,getdate()) > 21 

where dateofbirth < dateadd(yy,-21,getdate()) 

即:任何對列的操作都将導緻表掃描,它包括資料庫函數、計算表達式等等,查詢時 要盡可能将操作移至等号右邊。