1、一条SQL语句插入多条数据.
减少了数据库连接的I/O开销; 合并后日志量减少了。
INSERT INTO `insert_table` (`datetime`, `uid`, `content`, `type`) VALUES ('0', 'userid_0', 'content_0', 0);
INSERT INTO `insert_table` (`datetime`, `uid`, `content`, `type`) VALUES ('1', 'userid_1', 'content_1', 1);
修改成:
INSERT INTO `insert_table` (`datetime`, `uid`, `content`, `type`) VALUES ('0', 'userid_0', 'content_0', 0), ('1', 'userid_1', 'content_1', 1);
2、在事务中进行插入处理。减少创建事务的消耗。
START TRANSACTION;
INSERT INTO `insert_table` (`datetime`, `uid`, `content`, `type`) VALUES ('0', 'userid_0', 'content_0', 0);
INSERT INTO `insert_table` (`datetime`, `uid`, `content`, `type`) VALUES ('1', 'userid_1', 'content_1', 1);
...
COMMIT;
3、数据按照主键排序后插入。无序的记录会增大维护索引的成本
我们可以参照InnoDB使用的B+tree索引,如果每次插入记录都在索引的最后面,对索引调整较小;如果在索引中间,需要B+tree进行分裂合并等处理,会消耗比较多计算资源,并且插入记录的索引定位效率会下降,数据量较大时会有频繁的磁盘操作。
4、禁用索引
在导入数据时,如果我们需要同时创建索引,速度就会变慢。我们可以在导入数据前禁用索引,在导入完成后再重新启用索引。
table_name DISABLE KEYS;
4、load data local infile "test.txt" into table tb_cash_data fields terminated BY',';
速度更快,因为它是直接将数据从文件中读取进来,而不是逐条执行SQL语句。