【问题标题】:What is the difference between count and select('DISTINCT COUNT(xxx)') in ActiveRecord?ActiveRecord 中的 count 和 select('DISTINCT COUNT(xxx)') 有什么区别?
【发布时间】:2016-02-10 18:39:55
【问题描述】:

我有两个相似的查询:

StoreQuery.group(:location).count(:name)

StoreQuery.group(:location).select('DISTINCT COUNT(name)')

我原以为结果会完全一样,但事实并非如此。两者有什么区别?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    不同之处在于第一个查询计算所有名称,第二个查询计算唯一名称,忽略重复。如果您多次列出某些名称,它们将返回不同的数字。

    【讨论】:

      【解决方案2】:

      有了这个样本数据

      id | name | location |
      ---+------+----------+ 
      1  | NULL | US
      2  | A    | UK
      3  | A    | UK
      4  | B    | AUS
      

      让我们检查生成的查询结果

      第一次查询

      StoreQuery.group(:location).count(:name)
      

      生成的查询:

      SELECT location, COUNT(name) AS count FROM store_queries GROUP BY location
      

      结果:

      {US => 0, UK => 2, AUS => 1}
      

      第二次查询

      StoreQuery.group(:location).select('DISTINCT COUNT(name)')
      

      生成的查询:

      SELECT DISTINCT COUNT(name) FROM store_queries GROUP BY location
      

      结果:

      ActiveRecord::Relation [StoreQuery count: 0, StoreQuery count: 1, StoreQuery count: 1]
      # Mean {US => 0, UK => 1, AUS => 1}
      

      因此差异将是:

                       |1st query | 2nd query |
                       |----------+-----------+
      # returned fields|    2     |    1      |
           distinction |    no    |    yes    |
      

      顺便说一句,rails 支持这个:

      StoreQuery.group(:location).count(:name, distinct: true)
      

      【讨论】:

        猜你喜欢
        • 2017-12-19
        • 2011-02-22
        • 2020-03-02
        • 1970-01-01
        • 2020-11-10
        • 1970-01-01
        • 2010-09-08
        • 2014-06-09
        相关资源
        最近更新 更多