简体   繁体   English

如何在Rails 3 Active Record查询中一起选择对象和计数?

[英]How do I select an object and a count together in Rails 3 Active Record Query?

How do I do something like this in active query? 如何在主动查询中执行类似的操作?

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

I tried this in active query: 我在活动查询中尝试了这个:

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

The resultset i get back contains only the products that are sorted in the correct count order, but no count value. 我返回的结果集仅包含按正确计数顺序排序的产品,而没有计数值。 I did a .to_sql and it returns the correct sql. 我做了一个.to_sql,它返回了正确的sql。

How can I do this or something similar while being efficient on the db? 如何在数据库上高效地执行此操作或类似操作?

Another related question is, how do I do a .select("product.*) or .group("product.*") in active query? Right now I have to list every field out, eg. .group("product.id, product.name, product.price...etc") 另一个相关的问题是,如何在活动查询中执行.select("product.*).group("product.*") ?现在,我必须列出每个字段,例如.group("product.id, product.name, product.price...etc")

@Kevin, @凯文

Actually you are getting back product_counts the only thing to be aware of is that virtual attributes will not be displayed in the console so if you have: 实际上,您要返回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

Question 2: Not sure what you are trying to achieve with group("product.*"), if you want to get distinct rows you can use DISTINCT in your select eg Product.select("DISTINCT *") 问题2:不确定要使用group(“ product。*”)实现什么,如果要获得不同的行,可以在select中使用DISTINCT,例如Product.select(“ DISTINCT *”)

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

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