[英]Why Rails ActiveRecord generates 'count(distinct model.id)' for '.count' when 'includes' is used
I am using Rails 3.0.11
with MySQL 5.1
and today I realized that it generates an unexpected SQL statement when calling count
on a ActiveRecord::Relation
. 我将
Rails 3.0.11
与MySQL 5.1
,今天我意识到在ActiveRecord::Relation
上调用count
时,它会生成意外的SQL语句。
More details: 更多细节:
I have the model Profile
which belongs to an Account
. 我拥有属于
Account
的模型Profile
。 Assuming that I do the following: 假设我执行以下操作:
p = Profile.includes(:account).where("accept_threshold >= 0")
p.count
( accept_threshold
is an attribute of Profile
) (
accept_threshold
是Profile
的属性)
the generated SQL statement is: 生成的SQL语句为:
SELECT COUNT(DISTINCT `profiles`.`id`) FROM `profiles` LEFT OUTER JOIN `accounts` ON `accounts`.`id` = `profiles`.`account_id` WHERE (accept_threshold >= 0)
This is really a surprise to me. 这真的让我感到惊讶。 I would expect:
我期望:
SELECT COUNT(*) FROM `profiles` LEFT OUTER JOIN `accounts` ON `accounts`.`id` = `profiles`.`account_id` WHERE (accept_threshold >= 0)
On the other hand, the following piece of code: 另一方面,下面的代码段:
p = Profile.where("accept_threshold >= 0")
p.count
generates 产生
SELECT COUNT(*) FROM `profiles` WHERE (accept_threshold >= 0)
Do you know why is this the case? 你知道为什么会这样吗?
How can I force it to generate COUNT(*)
instead of COUNT(DISTINCT `profiles`.`id`)
? 如何强制它生成
COUNT(*)
而不是COUNT(DISTINCT `profiles`.`id`)
?
I have tried 我努力了
p.count(:select => "*")
but it does not work. 但它不起作用。
If it didn't do a count distinct it would be count of the number of account
records where the accept_threshold
is >= 0
. 如果没有做不同的计数,那将是
accept_threshold
>= 0
的account
记录数的计数。
You are after a count of profile
records, not a count of account
records. 您需要计算
profile
记录, 而不是 account
记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.