如何在 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")
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.
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")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@Kevin,
实际上您正在返回product_counts,唯一需要注意的是虚拟属性不会显示在控制台中,因此如果您有:
问题2:
不确定你想用 group("product.*") 实现什么,如果你想获得不同的行,你可以在选择中使用 DISTINCT,例如 Product.select("DISTINCT *")
@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:
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 e.g. Product.select("DISTINCT *")