gpt4 book ai didi

mysql - 无法选择按created_at分组的行

转载 作者:行者123 更新时间:2023-11-29 08:26:53 25 4
gpt4 key购买 nike

我有 table :

+----+----------------------+---------------------+
| 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 查询它时,它完美地按照我想要的方式工作

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

但是当我尝试将此查询转换为 ActiveRecord 语法时,它返回 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 中不起作用?

在我的rails项目中使用Rails 4.0.0、Ruby 2.0、mysql db。

最佳答案

我认为您只是对控制台输出有点困惑。

你是这样说的:

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

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

不用担心,您选择的值确实存在。如果你说:

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

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

关于mysql - 无法选择按created_at分组的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17714693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com