【问题标题】:How do I select an object and a count together in Rails 3 Active Record Query?如何在 Rails 3 Active Record Query 中同时选择对象和计数?
【发布时间】:2011-06-25 01:43:32
【问题描述】:

我如何在主动查询中做这样的事情?

select product.*, count(product_id) AS product_counts
group by(product.*) 
order by product_counts;

我在主动查询中试过这个:

Product.select("product fields, count(product_id) AS product_counts").group("product fields").order(product_counts)

我返回的结果集仅包含按正确计数顺序排序的产品,但没有计数值。我做了一个 .to_sql,它返回了正确的 sql。

如何在提高数据库效率的同时执行此操作或类似操作?

另一个相关问题是,如何在活动查询中执行.select("product.*).group("product.*")?现在我必须列出每个字段,例如。 .group("product.id, product.name, product.price...etc")

【问题讨论】:

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


    【解决方案1】:

    @凯文,

    实际上您正在返回 product_counts 唯一需要注意的是虚拟属性不会显示在控制台中,所以如果您有:

    products = select product.*, count(product_id) AS product_counts
    group by(product.*) 
    order by product_counts;
    
    #You can access the product_counts just as you would expect
    products.first.product_counts
    

    问题 2: 不确定你想用 group("product.*") 实现什么,如果你想获得不同的行,你可以在你的选择中使用 DISTINCT,例如Product.select("DISTINCT *")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 2017-10-14
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多