代码之家  ›  专栏  ›  技术社区  ›  Shpigford

将数据库结果分成4组

  •  0
  • Shpigford  · 技术社区  · 6 年前

    我有一张数十万艺术家的表格,每天我都会运行一个后台工作,更新这些艺术家的各种外部资源。

    每天一次完成这些任务会让那些外部API不知所措,因此我想将该表分成4组,然后每天运行4次这些后台作业(即每6小时一次)。

    如何将这些数据库结果分成4组?

    起初我只打算做2组,然后根据“如果艺术家ID是偶数/奇数”进行查询,但不知道如何做4组。

    理想情况下,我会在查询本身中这样做( Artist.where("id % 2 = ?", "0")

    2 回复  |  直到 6 年前
        1
  •  4
  •   Pablo    6 年前

    运行这些查询(每6小时一次)

    Artist.where("id % 4 = ?", 0) #Run at 00:00
    
    Artist.where("id % 4 = ?", 1) #Run at 06:00
    
    Artist.where("id % 4 = ?", 2) #Run at 12:00
    
    Artist.where("id % 4 = ?", 3) #Run at 18:00
    
        2
  •  1
  •   arieljuod    6 年前

    您只需计算总数,除以并使用偏移和限制:

    group_amount = Model.all.count/4
    
    scope = Model.limit(group_amount)
    
    first_group = scope
    second_group = scope.offset(group_amount)
    third_group = scope.offset(group_amount*2)
    fourth_group = Model.offset(group_amount*3) #not using limit in case you have new record on that table