gpt4 book ai didi

ruby-on-rails - Ruby on Rails 平均方法导致 n+1 次查询

转载 作者:数据小太阳 更新时间:2023-10-29 06:58:23 27 4
gpt4 key购买 nike

我有以下脚本:

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]]

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

最佳答案

Why includes is not working with aggregate methods?

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

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

关于ruby-on-rails - Ruby on Rails 平均方法导致 n+1 次查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49390861/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com