阅读背景:

用一条mysql语句插入多条数据

来源:互联网 

       假设有一个数据表A:

id name title addtime

        如果须要插入n条数据 :

$time= time();
$data = array(
  array(
   "name"=>"name1","title"=>"title1","addtime"=>$time;
  ),
  array(
   "name"=>"name2","title"=>"title2","addtime"=>$time;
  ),
  array(
   "name"=>"name3","title"=>"title3","addtime"=>$time;
  ),
  ...
  array(
   "name"=>"nameN","title"=>"titleN","addtime"=>$time;
  ),
  
);

   之前我的想法会是,通过数据结构多条插入语句,重复调用 。如:     

$sql1 = "INSERT INTO `A`(`name`,`title`,`addtime`)VALUES ("name1","title1","".$time."")";
$sql2 = "INSERT INTO `A`(`name`,`title`,`addtime`)VALUES ("name2","title2","".$time."")";
......
$sqlN = "INSERT INTO `A`(`name`,`title`,`addtime`)VALUES ("nameN","titleN","".$time."")";

   以后发明了sql的insert语句可以一次插入多条:

$sql = "INSERT INTO `A`(`name`,`title`,`addtime`)VALUES ("name1","title1","".$time.""),";
$sql .= "("name2","title2","".$time.""),";
$sql .= "("name3","title3","".$time.""),";
.....
$sql .= "("nameN","titleN","".$time."")";

       通过","号将多个数据分隔开来,便可以够能过一条sql操作来解决多个数据的插入,之前实验时,在插入数据条数为30的情形下,一次插入与屡次插入一样数据的速度相比,一次插入快了近9倍。同时,由于插入操作只有一次,所以也相似事务操作,插入失败则全失败,插入胜利则全胜利,使数据的管理更加便利。所以,如果有多条数据须要插入同一个表的,尽可能用这类方法。

之前插入多条数据库记载时,常这么写:

$b = 14;

for($a=0;$a<100;$a++){

   $sql = " INSERT INTO `roles` (`uid`,`rid`) VALUES (".$a.",".$b.")";

   mysql_query($sql);

}

但这类写法效力低下,须要屡次履行sql语句。如果你用过phpmyadmin导入数据,其实你会发明,上面的语句其实可以这么写

   INSERT INTO `roles` (`uid`,`rid`) VALUES
       (534,14),(535,14),(536,14),(537,14),(539,14)

所以本来的代码可以这么改写

 $b = 14;

for($a=0;$a<100;$a++){

  if($a==0)

     $sql = "INSERT INTO `roles` (`uid`,`rid`) VALUES (".$a.",".$b.")";

  else

    $sql. = ",(".$a.",".$b.")";

}

mysql_query($sql);

分享到: