简体   繁体   English

使用Rails中的include优化查询4

[英]Optimize query using include in rails 4

I need to optimize this query because it's taking more time and I want to approve group with group_category and user_comments . 我需要优化此查询,因为这需要花费更多时间,并且我希望批准使用group_categoryuser_comments分组。

@latest = Group.scope_approved
               .order('id desc')
               .includes(:group_category, :user_comments)
               .paginate(page: params[:page], per_page: 10)

There is thousands of records in group. 组中有成千上万的记录。

I am using 'mysql2', '~> 0.3.18' 我正在使用'mysql2','〜> 0.3.18'

Any idea? 任何想法?

(from Comment) (摘自评论)

Group Load (5.4ms) 
SELECT  groups.*
    FROM  groups
    WHERE  groups.approved = 1
    ORDER BY  id desc
    LIMIT  10 OFFSET 0

GroupCategory Load (1.2ms) 
SELECT  group_categories.*
    FROM  group_categories
    WHERE  group_categories.id IN (16, 3, 10, 1, 14)

UserComment Load (73635.3ms) 
SELECT  user_comments.*
    FROM  user_comments
    WHERE  user_comments.commentable_type = 'Group'
      AND  user_comments.commentable_id IN (67142, 67141, 67140,
                67137, 67136, 67135, 67134, 67131, 67130, 67129)

(61.3ms)
SELECT  COUNT(*)
    FROM  groups
    WHERE  groups.approved = 1 

user_comments would benefit from INDEX(commentable_type, commentable_id) (in that order). user_comments将受益于INDEX(commentable_type, commentable_id)user_comments顺序)。 This would speed up the 3rd query. 这将加快第三查询。

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

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