【问题标题】:Rails 4 + ActiveRecord + postgresql + group by do not work?Rails 4 + ActiveRecord + postgresql + group by 不工作?
【发布时间】:2016-04-13 14:48:42
【问题描述】:

我想通过 ActiveRecord 进行以下查询,但我不能。

SELECT
  catalog_product_id,
  COUNT (catalog_product_id)
FROM
  sc_items
WHERE sc_items.shopping_cart_id = 34
GROUP BY
  catalog_product_id;
BEGIN

Table: 
scItems(catalog_product_id, shopping_cart_id)
[1,1]
[2,1]
[2,1]
[2,1]

我正在做以下代码 ruby​​ 代码:

sc_items.select("catalog_product_id, count(catalog_product_id) as count").group("catalog_product_id")

生成这个sql:

SELECT catalog_product_id, count(catalog_product_id) as count FROM "sc_items" WHERE "sc_items"."shopping_cart_id" = $1 GROUP BY catalog_product_id  [["shopping_cart_id", 34]]

我得到了这个结果:

#<ActiveRecord::AssociationRelation [#<ScItem id: nil, catalog_product_id: 1>, #<ScItem id: nil, catalog_product_id: 3>]> 

另一方面,如果我执行上面的sql:

res = ActiveRecord::Base.connection.execute(sql)
res.class
res.to_a

我明白了:

#<PG::Result:0x007fcb3720bea8 status=PGRES_TUPLES_OK ntuples=2 nfields=2 cmd_tuples=2> 
PG::Result 
[{"catalog_product_id"=>"2", "count"=>"3"}, {"catalog_product_id"=>"1", "count"=>"1"}] 

这是正确的结果,如何使用 ActiveRecord 进行此查询?又为什么如果sql相同,activeRecord缺少catalog_product_id的id呢?

附加信息:

  • 'rails','4.2.0'
  • 'pg', '~> 0.18.1'
  • 红宝石'2.1.2'

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord group-by


    【解决方案1】:

    我相信你有一个名为 ScItem 的模型

    ScItem.where(shopping_cart_id: 34).group(:catalog_product_id).count
    

    您可以找到有关分组依据和计数here的更多详细信息

    【讨论】:

      【解决方案2】:

      按我使用过的某些属性对整个表格进行分组

      ScItem.unscoped.group(:catalog_product_id).count
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-31
        • 1970-01-01
        • 2015-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多