简体   繁体   English

为什么当使用'includes'时Rails ActiveRecord会为'.count'生成'count(distinct model.id)'

[英]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.11MySQL 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_thresholdProfile的属性)

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 >= 0account记录数的计数。

You are after a count of profile records, not a count of account records. 您需要计算profile记录, 而不是 account记录。

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

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