【问题标题】:What is error? i'm trying to fill table with random values什么是错误?我正在尝试用随机值填充表
【发布时间】:2022-12-09 19:42:10
【问题描述】:

我有两个相似的表:

CREATE TABLE `t1` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`c1` int(11) NOT NULL DEFAULT '0',
`c2` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_c1` (`c1`)
) ENGINE=InnoDB;

CREATE TABLE `t2` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`c1` int(11) NOT NULL DEFAULT '0',
`c2` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_c1` (`c1`)
) ENGINE=InnoDB;

我想用随机值填充两个表:

drop procedure if exists random_records;
truncate table t1;
truncate table t2;
delimiter $$

create procedure random_records(n int)
begin
set @i=1;
set @m=100000;
while @i <= n do
    insert into t1(c1,c2) values(rand()*@m,rand()*@m);
    insert into t2(c1,c2) values(rand()*@m,rand()*@m);
   set @i=@i+1;
end while;
end $$

delimiter ;

call random_records(100);
select * from t1 limit 10;
select * from t2 limit 10;
select count(*) from t1;
select count(*) from t2;

这是我在表 t1 中看到的内容:

我不明白为什么会有很多'0'和'1' 函数 count() 为 t1 返回 210,为 t2 返回 208——还有一个谜

【问题讨论】:

    标签: mysql random insert


    【解决方案1】:

    在两个表的c1c2 列中存在许多零和一的最可能原因是rand() 函数返回的数字非常小。这是因为用于缩放由rand()生成的随机数的@m变量设置为相对较低的值100,000。

    因此,生成的随机数大多介于 0 和 0.00001 之间,这就是为什么您会在表中看到许多 0 和 1。要解决此问题,您可以将 @m 的值增加到更高的数字,例如 1,000,000 甚至 10,000,000,以生成更大的随机数。

    至于两个表中行数的差异,可能是因为random_records过程中的insert语句没有被自动执行。

    这意味着 insert 语句之一可能会失败,从而导致向其中一个表中插入更少的行。要解决此问题,您可以将插入语句包装在事务中以确保它们作为单个工作单元执行。

    例如,您可以按如下方式修改random_records过程:

    drop procedure if exists random_records;
    truncate table t1;
    truncate table t2;
    delimiter $$
    
    create procedure random_records(n int)
    begin
    set @i=1;
    set @m=1000000;
    
    start transaction;
    
    while @i <= n do
        insert into t1(c1,c2) values(rand()*@m,rand()*@m);
        insert into t2(c1,c2) values(rand()*@m,rand()*@m);
       set @i=@i+1;
    end while;
    
    commit;
    end $$
    
    delimiter ;
    

    这应该确保 insert 语句以原子方式执行,并且两个表中的行数是一致的。

    【讨论】:

      猜你喜欢
      • 2013-12-01
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      • 2017-12-31
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多