MySQL insert效能最佳化筆記

來源:互聯網
上載者:User

對於一些資料量較大的系統,面臨的問題除了是查詢效率低下,還有一個很重要的問題就是插入時間長。我們就有一個業務系統,每天的資料匯入需要4-5個鐘。這種費時的操作其實是很有風險的,假設程式出了問題,想重跑操作那是一件痛苦的事情。因此,提高大資料量系統的MySQL insert效率是很有必要的。

經過對MySQL的測試,發現一些可以提高insert效率的方法,供大家參考參考。

1. 一條SQL語句插入多條資料。

常用的插入語句如:

  1. INSERT INTO `insert_table` (`datetime`, `uid`, `content`, `type`) VALUES ('0', 'userid_0', 'content_0', 0); 
  2. INSERT INTO `insert_table` (`datetime`, `uid`, `content`, `type`) VALUES ('1', 'userid_1', 'content_1', 1); 

修改成:

INSERT INTO `insert_table` (`datetime`, `uid`, `content`, `type`) VALUES ('0', 'userid_0', 'content_0', 0), ('1', 'userid_1', 'content_1', 1); 

修改後的插入操作能夠提高程式的插入效率。這裡第二種SQL執行效率高的主要原因有兩個,一是減少SQL語句解析的操作, 只需要解析一次就能進行資料的插入操作,二是SQL語句較短,可以減少網路傳輸的IO。

這裡提供一些測試對比資料,分別是進行單條資料的匯入與轉化成一條SQL語句進行匯入,分別測試1百、1千、1萬條資料記錄。

記錄數 單條資料插入 多條資料插入
1百 0.149s 0.011s
1千 1.231s 0.047s
1萬 11.678s 0.218s
  • 1
  • 2
  • 下一頁

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.