简体   繁体   English

通过计数查询加速Active Record组

[英]Speed up Active Record group by count query

How can I speed up the following query? 如何加快以下查询的速度? I'm look to find record with 6 or less unique values of fb_id . 我希望找到具有6个或更少的fb_id唯一值的fb_id The select doesn't seem to be adding much in terms of time but instead it's the group and count . 选择似乎并没有增加太多时间,而是groupcount Is there an alternate way to query? 有其他查询方式吗? I added an index on fb_id and it only sped up the query by 50% 我在fb_id上添加了索引,它仅使查询速度提高了50%

FbGroupApplication.group(:fb_id).where.not(
  fb_id: _get_exclude_fb_group_ids
).group(
  "count_fb_id desc"
).count(
  "fb_id"
).select{|k, v| v <= 6 }

The query is looking for FbGroupApplications that have 6 or less applications to the same fb_id 该查询正在查找对同一fb_id具有6个或更少应用程序的fb_id

Passing a block to the select method made Rails trigger the SQL, convert the found rows into ActiveRecord::Base's ruby object (record), and then perform a select on the array based of the block you gave. 将一个块传递给select方法后,Rails会触发SQL,将找到的行转换为ActiveRecord :: Base的ruby对象(记录),然后根据您给出的块在数组上执行选择。 This whole process is costly (ruby is not good at this). 这整个过程成本很高(红宝石对此不擅长)。

You can "delegate" the responsibility of comparing the count vs 6 to the database with a having clause: 您可以having hading子句“委托”将count vs 6与数据库进行比较的职责:

FbGroupApplication
  .group(:fb_id)
  .where.not(fb_id: _get_exclude_fb_group_ids)
  .having('count(fb_id) <= 6')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM