2012-07-11 114 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 

如果那仍然太慢...购买更多的硬件可能有帮助也是。

相关问题