Insert multiple data records using one mysql statement and multiple data records using one mysql statement
Assume that there is A data table:
Id name title addtime
To insert n data entries:
$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; ), );
Previously, my idea was to construct multiple insert statements through data and call them cyclically. For example:
$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."')";
After that, you can insert Multiple SQL insert statements at a time:
$sql = "INSERT INTO `A`(`name`,`title`,`addtime`)VALUES ('name1','title1','".$time."'),";$sql .= "('name2','title2','".$time."'),";$sql .= "('name3','title3','".$time."'),";.....$sql .= "('nameN','titleN','".$time."')";
By separating multiple data with the ",", you can use one SQL operation to insert multiple data. In the previous test, when the number of inserted data entries is 30, one insert is nearly nine times faster than multiple inserts of the same data. At the same time, because there is only one insert operation, it is similar to a transaction operation. If the insertion fails, all of them fail. If the insertion succeeds, all are successful, making data management more convenient. Therefore, if multiple data entries need to be inserted into the same table, try this method.
This is often the case when inserting multiple database records:
$b = 14;for($a=0;$a<100;$a++){ $sql = " INSERT INTO `roles` (`uid`,`rid`) VALUES (".$a.",".$b.")"; mysql_query($sql);}
However, this writing method is inefficient and requires multiple SQL statements to be executed. If you have used phpmyadmin to import data, you will find that the above statement can actually be written in this way.
INSERT INTO `roles` (`uid`,`rid`) VALUES (534,14),(535,14),(536,14),(537,14),(539,14)
So the original code can be rewritten as follows:
$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);
Mysql insert statements insert multiple duplicate records in the database once.
Paste the code...
Can I run insert to insert multiple data records at a time in mysql?
Yes:
In this case, let's give you an example:
Insert into 'mytest'. 'hello '(
'Id ',
'Name'
)
VALUES (
NULL, 'qq'
),(
NULL, 'ww'
),(
NULL, 'ee'
),(
NULL, 'rr'
),(
NULL, 'TT'
);