Mysql需要很长时间才能插入和更新Yii Framework

时间:2016-11-15 04:49:02

标签: php mysql yii2

想要插入或更新近10000条记录。插入for循环需要很长时间。尝试替代方式它只插入值,但在duplicate_key条目上显示错误。

  $var=0;

  if($method == 1)
  {  

// $sql5 is the current way trying but shows error

  $sql5='insert into stu_regnum_hall(hall_name,row,column,register_number,subject_code,exam_date,session,unique_key) values';
for ($i = 0; $i <=$arr_length; $i++)
{
for ($j = 1; $j <= 5; $j++)
{
for($k=0;$k<=4;$k++)
{
if(isset($show[$var+$k]))
{
if($k==0)
{
$hall_name=$arr1[$i];
$row=$j;
}
$column=$k+1;
$reg_num=$show[$var+$k];
$sub_code=$newArr12[$var+$k];
$unique_key=$reg_num.$date.$session;

//current way to insert This is taking too long time to store nearly 10000 records                                                                                

Yii::$app->db->createCommand('insert into stu_regnum_hall(hall_name,row,column,register_number,subject_code,exam_date,session,unique_key) values ("'.$hall_name.'","'.$row.'","'.$column.'","'.$reg_num.'","'.$sub_code.'","'.$date.'","'.$session.'","'.$unique_key.'") ON DUPLICATE KEY UPDATE hall_name ="'.$hall_name.'",row="'.$row.'",column="'.$column.'",register_number="'.$reg_num.'",subject_code="'.$sub_code.'",exam_date="'.$date.'",session="'.$session.'",unique_key="'.$unique_key.'"')->query();                               

//concatenation of $sql5 
$sql5.='("'.$hall_name.'","'.$row.'","'.$column.'","'.$reg_num.'","'.$sub_code.'","'.$date.'","'.$session.'","'.$unique_key.'") ON DUPLICATE KEY UPDATE hall_name= "'.$hall_name.'",row="'.$row.'",column="'.$column.'",register_number="'.$reg_num.'",subject_code="'.$sub_code.'",exam_date="'.$date.'",session="'.$session.'",unique_ key="'.$unique_key.'",';   
   }
else
{
break;
}
}
$var=$var+5;
 }
}

$sql5.='("");';

   // This is the required answer but getting   error                                                                                                      
    Yii::$app->db->createCommand($sql5)->query();
    }

$ sql5查询应该在这个

中工作

1 个答案:

答案 0 :(得分:1)

使用一点自定义Yii2 batchInsertINSERT IGNOREREPLACE尝试ON DUPLICATE KEY UPDATE。它插入速度非常快。

$sql = Yii::$app->db->queryBuilder->batchInsert('your_table_name', ['column1', 'column2','column3',...], $dataArray);
// For IGNORE on Duplicate
//$sql = 'INSERT IGNORE' . mb_substr($sql, strlen('INSERT'));
// For Replace on Duplicate
//$sql = 'REPLACE' . mb_substr($sql, strlen('INSERT'));
// For Update on Duplicate
$sql .= ' ON DUPLICATE KEY UPDATE `column1` = VALUES(`column1`), `column2` = VALUES(`column2`), ...';

Yii::$app->db->createCommand($sql)->execute();

参考:http://www.yiiframework.com/doc-2.0/yii-db-querybuilder.html#batchInsert()-detail