mysql - Rails 事件记录没有 X 作为 Y 字段

标签 mysql ruby-on-rails activerecord

Rails 初学者,适用于 mysql 的查询 -- 选择 X 作为 Y 似乎不适用于 Rails 的查询。

字段 m1 的计数为“cnt”==> 事件记录不存在(给定的查询适用于 mysql)

AB.where("m = 1").group("UNIX_TIMESTAMP(m_timestamp) DIV 6048000 ").select("m_timestamp, count(m1) as cnt")
AB Load (3.5ms)  SELECT m_timestamp, count(m1) as cnt FROM `a_b` WHERE (m = 1) GROUP BY UNIX_TIMESTAMP(m_timestamp) DIV 6048000 
=> #<ActiveRecord::Relation [#<AB id: nil, m_timestamp: "2014-08-01 22:21:09">, #<AB id: nil, m_timestamp: "2014-10-05 00:15:23">, #<AB id: nil, m_timestamp: "2014-12-20 11:55:45">, #<AB id: nil, m_timestamp: "2015-02-04 23:45:29">, #<AB id: nil, m_timestamp: "2015-04-02 03:51:14">, #<AB id: nil, m_timestamp: "2015-06-19 22:25:06">]>     

上面的 mysql 查询 -- SELECT m_timestamp, count(m1) as cnt FROM 'a_b' WHERE (m = 1) GROUP BY UNIX_TIMESTAMP(m_timestamp) DIV 6048000 在 mysql 中有效。

如果我只使用计数,我将使用一些键获得分组计数 - 我不确定它是什么。

AB.where("m = 1").group("UNIX_TIMESTAMP(m_timestamp) DIV 6048000 ").count
{232=>72, 233=>69, 234=>73, 235=>76, 236=>58, 237=>15}

我希望 m_timestamp 成为上述结果的关键。我怎样才能做到这一点?

mysql 结果的示例输出为:

mysql> SELECT m_timestamp, count(user_id) as cnt FROM `a_b` WHERE (m = 1) GROUP BY UNIX_TIMESTAMP(m_timestamp) DIV 6048000  ORDER BY `a_b`.`m_timestamp` ASC;
+---------------------+-----+
| m_timestamp         | cnt |
+---------------------+-----+
| 2014-08-01 22:21:09 |  72 |
| 2014-10-05 00:15:23 |  69 |
| 2014-12-20 11:55:45 |  73 |
| 2015-02-04 23:45:29 |  76 |
| 2015-04-02 03:51:14 |  58 |
| 2015-06-19 22:25:06 |  15 |
+---------------------+-----+

mysql> select * from m_feedbacks LIMIT 5;
+----+-----------+-------+---------------------+---------+
| id | x_id      | m     | m_timestamp         | user_id |
+----+-----------+-------+---------------------+---------+
|  1 |         1 |     1 | 2015-02-04 23:45:29 |       1 |
|  2 |         1 |     2 | 2015-04-24 23:00:37 |       1 |
|  3 |         1 |     2 | 2014-09-25 02:51:37 |       1 |
|  4 |         1 |     0 | 2014-09-29 03:28:01 |       1 |
|  5 |         1 |     0 | 2014-12-11 16:15:09 |       1 |
+----+-----------+-------+---------------------+---------+
5 rows in set (0.00 sec)

提前致谢

最佳答案

您的第一种方法很接近,因为 select X as Y 确实有效。 inspect 方法不会显示此值。从数组中获取第一个值并对其调用 cnt 以查看它是否正常工作。

调用group时,key是group方法计算的值。

我认为得到你想要的最好的方法,你可以使用 pluck:

AB.where("m = 1").group("UNIX_TIMESTAMP(m_timestamp) DIV 6048000 ").pluck("m_timestamp, count(*)").to_h

关于mysql - Rails 事件记录没有 X 作为 Y 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31071122/

相关文章:

mysql - Rails、MySQL 和雪豹

javascript - 如何使用 javascript 以 Rails 形式获取本地时间?

从控制台调用时 MySQL 请求返​​回结果,但使用 ActiveRecord 请求时为空

ruby-on-rails - Rails ActiveRecord 正则表达式验证非强制字段

mysql - 从 MySQL 数据库中选择 friend ,然后选择他们的详细信息(可能需要加入)

ruby-on-rails - 将按钮添加到 Rails ActionText 工具栏

python - 在 Queue.task_done() 之后运行多线程代码

ruby-on-rails - rails : Joining the same table twice and querying a joined attribute

mysql - 如何在不点击按钮的情况下自动从 MySQL 获取数据到 Android?

MySQL 多选