我有两个 ID,它们对应于数据库中的一系列记录。我想分批处理 1000 条记录。假设这两个 ID 是 51234 和 59265。我想遍历它并确保处理所有记录。
我从一个 for 循环开始,如下所示
for(int i = 51234; i < 59265; i= i+1000) {
select * from database where id between i and i+1000;
//do the stuff
}
现在这在第 59234 条记录之前工作正常,最后 31 条记录呢?我也想在这次运行中处理它们。
我可能可以检查每次迭代中 i 的值是多少,并检查向查询中添加 1000 是否超过最大 ID 并调整 sql 查询。那是唯一的方法吗? for 循环在这里是正确的方法吗?
int batchSize=1000;
for(int i = 51234; i <= 59265; i+=batchSize) {
select * from database where id between i and Math.min(i+batchSize, 59265);
//do the stuff
}
示例输出:
between 51234 and 52234 actualBatch=1000
between 52234 and 53234 actualBatch=1000
between 53234 and 54234 actualBatch=1000
between 54234 and 55234 actualBatch=1000
between 55234 and 56234 actualBatch=1000
between 56234 and 57234 actualBatch=1000
between 57234 and 58234 actualBatch=1000
between 58234 and 59234 actualBatch=1000
between 59234 and 59265 actualBatch=31
由于 between 包含在内,因此每个批处理都有重叠。你可以改变它并使用不等式来解决这个问题:
int batchSize = 1000;
int start=51234;
int end=59265;
for(int i = start; i < end + 1; i+=batchSize) {
select * from database where id >= i and id < Math.min(i+batchSize, end);
}
示例输出:
id >= 51234 and id < 52234 actualBatch=1000
id >= 52234 and id < 53234 actualBatch=1000
id >= 53234 and id < 54234 actualBatch=1000
id >= 54234 and id < 55234 actualBatch=1000
id >= 55234 and id < 56234 actualBatch=1000
id >= 56234 and id < 57234 actualBatch=1000
id >= 57234 and id < 58234 actualBatch=1000
id >= 58234 and id < 59234 actualBatch=1000
id >= 59234 and id < 59266 actualBatch=32
我是一名优秀的程序员,十分优秀!