我很擅长优化我的查询,我有一个N + 1查询,它似乎需要一个计数器,但我不确定如何继续:
...
SQL (0.5ms) SELECT COUNT(*) AS count_id FROM (SELECT 1 FROM `photos` WHERE (`photos`.attachable_id = 4864 AND `photos`.attachable_type = 'Recipe')) AS subquery
SQL (2.1ms) SELECT COUNT(*) AS count_id FROM (SELECT 1 FROM `votes` WHERE (`votes`.voteable_id = 4864 AND `votes`.voteable_type = 'Recipe') AND (`votes`.`vote` = 1)) AS subquery
SQL (2.0ms) SELECT COUNT(*) AS count_id FROM (SELECT 1 FROM `votes` WHERE (`votes`.voteable_id = 4864 AND `votes`.voteable_type = 'Recipe') AND (`votes`.`vote` = 0)) AS subquery
SQL (0.3ms) SELECT COUNT(*) AS count_id FROM (SELECT 1 FROM `photos` WHERE (`photos`.attachable_id = 4865 AND `photos`.attachable_type = 'Recipe')) AS subquery
SQL (2.6ms) SELECT COUNT(*) AS count_id FROM (SELECT 1 FROM `votes` WHERE (`votes`.voteable_id = 4865 AND `votes`.voteable_type = 'Recipe') AND (`votes`.`vote` = 1)) AS subquery
SQL (2.4ms) SELECT COUNT(*) AS count_id FROM (SELECT 1 FROM `votes` WHERE (`votes`.voteable_id = 4865 AND `votes`.voteable_type = 'Recipe') AND (`votes`.`vote` = 0)) AS subquery
...
所以我有两件奇怪的事情在这里造成问题。我有这种多态vote
模型,我需要对它们进行总结,基本上如果有人投了一票,它在0
列上的值为vote
,并且{ {1}}如果用户投了票。但是看起来它会创建这个疯狂的查询。
我该如何解决这个问题?
我认为造成这种情况的事情在我看来是以这种方法开始的:
1
这就是我统计选票的方式:
<%= recipe.votes.tally %>
但是因为我正在为每个对象做这件事,所以我必须多次执行这个逻辑,我们最终会得到一个疯狂的N + 1.
答案 0 :(得分:1)
当你写作时,
我认为造成这种情况的事情在我看来是以这种方法开始的:
&LT; %= recipe.votes.tally%&gt;
通过在脚本/控制台中获取配方实例,您可以找到更多确定性 并执行 recipe.votes.tally 那里
不太确定,这有点模糊,但您是否可以考虑将您的计数方法放在食谱模型中? - 斯蒂芬