[英]How do I select an object and a count together in Rails 3 Active Record Query?
如何在主动查询中执行类似的操作?
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")
@凯文
实际上,您要返回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。*”)实现什么,如果要获得不同的行,可以在select中使用DISTINCT,例如Product.select(“ DISTINCT *”)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.