在mysql中插入多行

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

就像

INSERT....


UNION


INSERT....


UNION

(我需要插入2-3000行)

920895 次浏览

使用VALUES语法的INSERT语句可以插入多行。为此,需要包含多个列值列表,每个列表用圆括号括起来,并用逗号分隔。

例子:

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

Source .

如果数据在文本文件中,则可以使用加载数据文件

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

优化INSERT语句

您可以在上面的链接中找到更多关于如何加快insert语句的技巧。

只需使用SELECT语句获取所选列的很多行值,并将这些值一次性放入另一个表的列中。例如,columns "size"和“;price"test_b"和“;test_c"用“大小”列填充;和“;price"表“test_a";

BEGIN;
INSERT INTO test_b (size, price)
SELECT size, price
FROM   test_a;
INSERT INTO test_c (size, price)
SELECT size, price
FROM   test_a;
COMMIT;

代码被嵌入到BEGINCOMMIT中,只有当两个语句都有效时才运行它,否则直到那一点的整个运行将被撤回。

// 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')";

下面是一个PHP解决方案,用于n: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));

编辑:在@john的评论之后,我决定用一个更有效的解决方案来加强这个答案:

  • 将查询划分为多个较小的查询
  • 使用rtrim()来删除最后一个昏迷,而不是implod()
// limit of query size (lines inserted per query)
$query_values  = "";
$limit         = 100;
$table_1       = get_table_1_rows();
$table_2_fk_id = 123;


$query = "INSERT INTO `table` (
`table_1_fk_id`,
`table_2_fk_id`,
`insert_date`
) VALUES ";


foreach($table_1 as $row) {
$query_values .= "(".$row["table_1_pk_id"].", $table_2_fk_id, NOW()),";
    

// entire table parsed or lines limit reached :
// -> execute and purge query_values
if($i === array_key_last($table_1)
|| fmod(++$i / $limit) == 0) {
$db->query($query . rtrim($query_values, ','));
$query_values = "";
}
}