无法选择按created_at分组的行 [英] Can't select rows grouping by created_at

查看:66
本文介绍了无法选择按created_at分组的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有桌子:

+----+----------------------+---------------------+
| id | implemented_features | created_at          |
+----+----------------------+---------------------+
|  1 |                   19 | 2013-07-18 04:10:12 |
|  2 |                    6 | 2013-07-18 04:10:12 |
|  3 |                   26 | 2013-07-19 04:10:12 |
|  4 |                   11 | 2013-07-19 04:10:12 |
|  5 |                    1 | 2013-07-20 04:10:12 |
+----+----------------------+---------------------+

当我直接通过MySQL查询时,它可以按我的要求完美运行

When I query this directly via MySQL it works perfectly as I want

select date(created_at) as date, sum(implemented_features) as sum from summaries group by date(created_at);

但是当我尝试将此查询转换为ActiveRecord语法时,它将返回nil.

But when I try to convert this query to ActiveRecord syntax it returns me nil.

2.0.0p0 :035 > Summary.select("date(created_at) as date, sum(implemented_features)").group("date(created_at)")
  Summary Load (0.5ms)  SELECT date(created_at) as date, sum(implemented_features) FROM `summaries` GROUP BY date(created_at)
 => #<ActiveRecord::Relation [#<Summary id: nil>]> 

如您所见,两个示例中的最终查询均相等. 为什么在ActiveRecord情况下不起作用?

As you see, final queries are equal in both examples. Why it don't work in case of ActiveRecord?

在Rails项目中使用Rails 4.0.0,Ruby 2.0和mysql db.

Using Rails 4.0.0, Ruby 2.0, mysql db in my rails project.

推荐答案

我认为您对控制台输出感到有些困惑.

I think you're just a little confused by the console output.

您是在说这个

Summary.select("date(created_at) as date, sum(implemented_features)")...

,因此返回的Summary实例(包装在ActiveRecord::Relation中)不具有任何常见的Summary属性:无id,无created_at,无implemented_featured等.何时您在ActiveRecord对象上调用inspect,它想向您显示该对象内部的内容,这意味着它想向您显示所包含的数据库属性;您的Summary实例没有任何通常的属性,因此您会看到类似<Summary id: nil>的内容.

so the returned Summary instances (wrapped up in an ActiveRecord::Relation) don't have any of the usual Summary attributes: no id, no created_at, no implemented_featured, etc. When you call inspect on an ActiveRecord object, it wants to show you what's inside the object and that means that it wants to show you the contained database attributes; your Summary instances don't have any of the usual attributes so you see things like <Summary id: nil>.

不要害怕,您选择的值确实存在.如果您说:

Fear not, the values you selected really are there. If you say:

Summary.select(...).map(&:date)

您应该看到date(created_at) as date值.如果为sum(implemented_features)添加别名,则可以使用该别名作为方法名称来提取总和.

you should see the date(created_at) as date values. If you add an alias for the sum(implemented_features) then you can extract the sums by using that alias as a method name.

这篇关于无法选择按created_at分组的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆