Ruby on Rails平均方法导致n + 1个查询

时间:2018-03-20 17:40:38

标签: ruby-on-rails ruby

我有以下脚本:

User.includes(:owned_ratings).map{|x| x.owned_ratings.average(:score)}

调用x.owned_ratings.average(:score)会导致n + 1次查询:

   (0.2ms)  SELECT AVG("ratings"."score") FROM "ratings" INNER JOIN "video_chats" ON "ratings"."video_chat_id" = "video_chats"."id" WHERE "video_chats"."user_id" = $1  [["user_id", 4]]
   (0.1ms)  SELECT AVG("ratings"."score") FROM "ratings" INNER JOIN "video_chats" ON "ratings"."video_chat_id" = "video_chats"."id" WHERE "video_chats"."user_id" = $1  [["user_id", 1]]
   (0.1ms)  SELECT AVG("ratings"."score") FROM "ratings" INNER JOIN "video_chats" ON "ratings"."video_chat_id" = "video_chats"."id" WHERE "video_chats"."user_id" = $1  [["user_id", 5]]
   (0.1ms)  SELECT AVG("ratings"."score") FROM "ratings" INNER JOIN "video_chats" ON "ratings"."video_chat_id" = "video_chats"."id" WHERE "video_chats"."user_id" = $1  [["user_id", 7]]
   (0.1ms)  SELECT AVG("ratings"."score") FROM "ratings" INNER JOIN "video_chats" ON "ratings"."video_chat_id" = "video_chats"."id" WHERE "video_chats"."user_id" = $1  [["user_id", 3]]

为什么包含不使用聚合方法?有没有办法解决这个问题?我知道我可以自己实现平均方法并省略问题,但我想确保没有更好的解决方案。

3 个答案:

答案 0 :(得分:5)

  

为什么includes无法使用聚合方法?

因为在ruby中重新实现聚合方法是没有意义的,因为数据库服务器可以更快地完成工作。

事实上,如果这是你需要做的,那么准备和执行原始SQL查询可能会更好,这样整个迭代就在数据库中完成,因此避免了往返和N + 1(更不用说了)加载一切)。

答案 1 :(得分:3)

使用SQL实现这一点非常简单:

@users = User.select(
  'users.*, AVG(ratings.score) AS users.average_score'
).group_by('ratings.user_id').joins(:ratings)

@users.map(&:average_score)

答案 2 :(得分:2)

因为average实际上需要sql查询?尝试类似:

User.includes(:owned_ratings).map{ |x| x.owned_ratings.map(&:score).instance_eval { reduce(:+) / size.to_f } }

从此SO answer得到的数组中的平均值的方法。效率取决于有多少owned_ratings条记录。

Sergio Tulentsev是对的,在db方面做得更好