Home > Database > Mysql Tutorial > 用一条mysql语句插入多条数据

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

WBOY
Release: 2016-06-07 16:28:24
Original
954 people have browsed it

假如有一个数据表A: idnametitleaddtime 如果需要插入n条数据 : $time= time();$data = array( array( 'name'='name1','title'='title1','addtime'=$time; ), array( 'name'='name2','title'='title2','addtime'=$time; ), array( 'name'='name3','title'='t

       假如有一个数据表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;
  ),
  
);
Copy after login

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

$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."')";
Copy after login

之后发现了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."')";
Copy after login

通过","号将多个数据分隔开来,就可以能过一条sql操作来解决多个数据的插入,之前试验时,在插入数据条数为30的情况下,一次插入与多次插入同样数据的速度相比,一次插入快了近9倍。同时,因为插入操作只有一次,所以也类似事务操作,插入失败则全失败,插入成功则全成功,使数据的管理更加方便。所以,如果有多条数据需要插入同一个表的,尽量用这种方式。

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

$b = 14;

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

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

   mysql_query($sql);

}

Copy after login

但这种写法效率低下,需要多次执行sql语句。如果你用过phpmyadmin导入数据,其实你会发现,上面的语句其实可以这么写

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

Copy after login

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

 $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);
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template