One - One Code All

Blog Content

mysql快速插入百万数据

MySQL   2013-01-07 21:23:15

构建表:

create table user(
  id INT(10) NOT NULL AUTO_INCREMENT,
  username VARCHAR(64) NULL,
  sex tinyint(1) default 0,
  PRIMARY KEY ( id )
);


sql使用存储过程:

delimiter //                            #定义标识符为双斜杠
drop procedure if exists test;          #如果存在test存储过程则删除
create procedure test()                 #创建无参存储过程,名称为test
begin
    declare i int;                      #申明变量
    set i = 0;                          #变量赋值
    while i < 1000000 do                     #结束循环的条件: 当i大于10时跳出while循环
        insert into mytest.user (username,sex) values((select a.username from (select max(id)+1 as username from mytest.user) as a),(SELECT FLOOR(0 + (RAND() * 2))));
        set i = i + 1;                  #循环一次,i加一
    end while;                          #结束while循环
    select * from user;                 #查看test表数据
end
//                                      #结束定义语句
call test();


sql 插入数据取sid最大值加一保存

insert into A(id,sid) 

 values(111111,(select case  when max(sid) IS NULL then '1' else max(sid)+1 end from A)) 

这里要考虑到数据库表内无数据,所以使用max(sid)要先判断下它是否为空,是空就赋值为1,不是空就在max(sid)的基础上+1,

还有就是你的SELECT语句是作为一个值来进行插入的,所以要用括号括上。


把结果集当作一个表,自我查询一遍, 不然报错:You can't specify target table '表名' for update in FROM clause



上一篇:Python两个列表里元素对应相乘,列表相除
下一篇:java中打印数组的5种方法

The minute you think of giving up, think of the reason why you held on so long.