首页 文章

在mysql中插入多行

提问于
浏览
350

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

喜欢

INSERT....

UNION

INSERT....

UNION

(我需要插入2-3000行)

5 回答

  • 49

    如果您的数据在文本文件中,则可以使用LOAD DATA INFILE .

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

    Optimizing INSERT Statements

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

  • -1

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

    Example:

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

    Source

  • 961
    // 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')";
    
  • -4
    BEGIN;
    INSERT INTO test_b (price_sum)
      SELECT price
      FROM   test_a;
    INSERT INTO test_c (price_summ) 
      SELECT price
    FROM   test_a;
    COMMIT;
    
  • 12

    这是一个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));
    

相关问题