在mysql中插入多行

如果我一次插入多行数据库查询更快:

喜欢

INSERT.... UNION INSERT.... UNION 

(我需要插入2-3000行)

使用VALUES语法的INSERT语句可以插入多行。 为此,请包含多个列值列表,每个列表值都包含在括号内,并用逗号分隔。

例:

 INSERT INTO tbl_name (a,b,c) VALUES (1,2,3), (4,5,6), (7,8,9); 

资源

如果你的数据在一个文本文件中,你可以使用LOAD DATA INFILE 。

从文本文件加载表格时,使用LOAD DATA INFILE。 这通常比使用INSERT语句快20倍。

INSERT语句的速度

您可以在上面的链接中find有关如何加快插入语句的更多提示。

您可以使用此脚本插入尽可能多的行。

 INSERT INTO tableName (column1,column2,column3,column4) VALUES ('value1' , 'value2', 'value3','value4'), ('value1' , 'value2', 'value3','value4'), ('value1' , 'value2', 'value3','value4'); 
 BEGIN; INSERT INTO test_b (price_sum) SELECT price FROM test_a; INSERT INTO test_c (price_summ) SELECT price FROM test_a; COMMIT; 

这是一个PHP解决scheme,可以用于:m(多对多关系)表:

 // get data $table_1 = get_table_1_rows(); $table_2_fk_id = 123; // prepare first part of the query (before values) $query = "INSERT INTO `table` ( `table_1_fk_id`, `table_2_fk_id`, `insert_date` ) VALUES "; //loop the table 1 to get all foreign keys and put it in array foreach($table_1 as $row) { $query_values[] = "(".$row["table_1_pk_id"].", $table_2_fk_id, NOW())"; } // Implode the query values array with a coma and execute the query. $db->query($query . implode(',',$query_values)); 
 // db table name / blog_post / menu / site_title // Insert into Table (column names separated with comma) $sql = "INSERT INTO product_cate (site_title, sub_title) VALUES ('$site_title', '$sub_title')"; // db table name / blog_post / menu / site_title // Insert into Table (column names separated with comma) $sql = "INSERT INTO menu (menu_title, sub_menu) VALUES ('$menu_title', '$sub_menu', )"; // db table name / blog_post / menu / site_title // Insert into Table (column names separated with comma) $sql = "INSERT INTO blog_post (post_title, post_des, post_img) VALUES ('$post_title ', '$post_des', '$post_img')";