Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 优化代码以填充大型表中的新列_Mysql_Ruby On Rails_Ruby - Fatal编程技术网

Mysql 优化代码以填充大型表中的新列

Mysql 优化代码以填充大型表中的新列,mysql,ruby-on-rails,ruby,Mysql,Ruby On Rails,Ruby,我将向一个有3700万行的表中添加一个新列。该列将包含一个关联ID 简单模型: 类SeenEpisode

我将向一个有3700万行的表中添加一个新列。该列将包含一个关联ID

简单模型:

类SeenEpisode
这是我能想到的最快的方法:

seen_episodes = SeenEpisode.where("show_id IS NULL")
seen_episodes.find_in_batches do |batch| #batch size is 1000
  batch.group_by(&:season_id).each do |season_id, seen_episodes|
    #all seen_episodes with the same season_id, ensures the same show_id
    show_id = seen_episodes.first.episode.show_id
    seen_episodes.each do |seen_episode|
      seen_episode.update_column(:show_id, show_id) #skip validations and callbacks
    end
  end
end
当前的开发测试表明,填充10000条记录大约需要2分钟。
假设生产需要1分钟,由于更好的硬件和mysql配置,每百万条记录仍需要100分钟。大概60个小时


有没有可能有一种更快的方法来实现这一点呢?

如果批量写入,速度会快几个数量级。我的意思是,不发送个人信件

update episodes set show_id = 1 where episode_id = 1;
update episodes set show_id = 1 where episode_id = 2;
update episodes set show_id = 1 where episode_id = 3;
您应该将它们分组为一个单独的写入

update episodes set show_id = 1 where episode_id in (1, 2, 3);
或者,像这样的东西可以起作用:

select season_id, show_id 
from episodes 
where show_id is not null 
group by season_id;
这将为每个
季节\u id
获取一个
show\u id
。然后只需循环这些行并启动大规模更新(为了简单起见,您可能会在ruby中执行SQL语法)


我同意你的第一个建议。由于批处理大小为100000,我现在每100000条记录的时间减少到30秒左右,这意味着大约3小时(从60小时减少到30秒),这是在我缓慢开发的机器上实现的:)非常感谢!
update episodes set show_id = @show_id where season_id = @season_id;