我想做一些类似的事情
User.select("users.id, count(whatever) as test")
但是rails只返回User.id而不返回计数。我不能用这样的东西
User.count(whatever)
因为我在一个非常复杂的SQL查询中使用了这个select。是否可以使用select helper获取计数值?
您确定以下查询返回User.id
吗?它不是抛出了一个错误,说"列在选择列表中无效,因为它既不包含在聚合函数中,也不包含在groupby子句中":
User.select("users.id, count(whatever) as test")
因为您使用的是count
,所以还应该使用group
方法,如下所示:
User.select("users.id, count(whatever) as test").group("users.id, whatever")
然后,得到的数组将包含users.id
和count(whatever)
。