2012-07-11 66 views
0

我必須一次插入超過200000條記錄,進入MySQL數據庫表,插入查詢導致性能問題,什麼可能是替代這一點。Substitute插入查詢超過200,000記錄在MySQL數據庫表

下面是我使用

$xml = simplexml_load_file("247electrical.xml"); 

foreach($xml->merchant as $merchant){ 

define('API', 'PS'); 
require_once('constants.inc.php'); 
require_once('classes/class.ClientFactory.php'); 
$oClient = ClientFactory::getClient(API_USERNAME, API_PASSWORD, API_USER_TYPE); $merchattrs=$merchant->attributes(); 
$aParams100 = array('iMerchantId' => array($merchattrs->id)); $merchantinfo= $oClient->call('getMerchant', $aParams100); 

//Get Products 

foreach($xml->merchant->prod as $product){ 

$attrs=$product->attributes(); 

//Insert Products into DB 
mysql_query('INSERT INTO productstemp (merchant_id, merchant_name, aw_product_id, merchant_product_id, product_name, description, category_id, merchant_category, aw_deep_link, aw_image_url, search_price, delivery_cost, merchant_image_url, aw_thumb_url, brand_name, delivery_time, display_price, in_stock, merchant_thumb_url, model_number, pre_order, stock_quantity, store_price, valid_from, valid_to, web_offer, merchantimage, cleancompany) VALUES("'.$merchattrs->id.'","'.$merchattrs->name.'","'.$attrs->id.'"," ","'.$product->text->name.'","'.$product->text->desc.'","'.$product->cat->awCatId.'","'.$product->cat->mCat.'","'.$product->uri->awTrack.'","'.$product->uri->awImage.'","'.$product->price->buynow.'","'.$product->price->delivery.'","'.$product->uri->mImage.'","'.$product->uri->awThumb.'","'.$product->brand->brandName.'","'.$product->delTime.'","'.$product->price->buynow.'","'.$attrs->in_stock.'","'.$product->uri->mThumb.'","'.$product->modelNumber.'","'.$attrs->pre_order.'","'.$attrs->stock_quantity.'","'.$product->price->store.'","'.$product->valFrom.'","'.$product->valTo.'","'.$attrs->web_offer.'","'.$merchantinfo->oMerchant->sLogoUrl.'","247electrical") ') 
or die(mysql_error());  

} 
} 

感謝

+0

我不明白,將這些信息放入數據庫的唯一方法是使用插入,所以你的問題是什麼? – jcho360 2012-07-11 14:33:36

+0

它的一個cron作業,我已經在一個PHP foreach循環中使用插入查詢,這使得腳本變得很慢,所以我需要另一個解決方法來完成這個任務,而不會減慢進程 – 2012-07-11 14:35:22

+0

爲什麼不使用Mysql TASK導入包含所有這些行的文件?或者創建一個調用將文件導入數據庫的過程的cronjob? – jcho360 2012-07-11 14:36:22

回答

0

我不認爲在INSERT查詢本身有問題的代碼。畢竟200.000插入對於mysql來說並不那麼重要。

首先,我猜這個文件讀起來很慢。 SimpleXML很方便,但對於大文件而言,它會導致巨大的內存開銷。考慮一下流式XML閱讀器,例如PHP的XMLReader

您正在向mysql服務器發送單個語句,這比發送一個巨大的語句要慢一些。另外,你的單一插入語句應該被包裝在一個事務中。如果處理10.000條記錄並插入它們,然後腳本死亡/ mysql服務器死亡等,會發生什麼情況?如何在沒有手動工作的情況下再次安全地啓動腳本(清除表,已經處理的查找等)。

除此之外,帶有許多VALUES的單個INSERT語句應該更快。我會讓你的PHP腳本輸出的查詢,以便它看起來到底是這樣的:

INSERT INTO table(field_1, field_2, field 3) 
VALUES('foo 1', 'bar 1', 'baz 1'), 
VALUES('foo 2', 'bar 2', 'baz 2'), 
... 

,然後通過導入該文件:

$ mysql ... credentials options etc ... < output.sql 

如果那仍然太慢...購買更多的硬件可能有幫助也是。