在mysql中插入多行

這篇文章是社區維基 。 編輯現有答案以改善此職位。 它當前不接受新的答案。 瞭解更多

若是一次插入多行,數據庫查詢會更快嗎: php

喜歡 html

INSERT....

UNION

INSERT....

UNION

(我須要插入2-3000行) mysql


#1樓

BEGIN;
INSERT INTO test_b (price_sum)
  SELECT price
  FROM   test_a;
INSERT INTO test_c (price_summ) 
  SELECT price
FROM   test_a;
COMMIT;

#2樓

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

#3樓

這是一個可與an:m(多對多關係)表一塊兒使用的PHP解決方案: sql

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

#4樓

使用VALUES語法的INSERT語句能夠插入多行。 爲此,請包括多個列值列表,每一個列值括在括號內並用逗號分隔。 數據庫

例: ide

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

資源 oop


#5樓

若是您的數據在文本文件中,則可使用LOAD DATA INFILEpost

從文本文件加載表時,請使用LOAD DATA INFILE。 這一般比使用INSERT語句快20倍。 優化

優化INSERT語句 spa

您能夠在上面的連接中找到有關如何加快插入語句的更多提示。

相關文章
相關標籤/搜索