[英]activerecord ruby row with max value in mysql table
I need to select from MySQL table table1
(it's shown below) all records with different 'foreign_row_id' values and group them by maximum datetime
value. 我需要从MySQL表
table1
(如下所示)中选择所有具有不同'foreign_row_id'值的记录,并按最大datetime
值对它们进行分组。 For example, from the table below I should select rows with id=2 and id=3. 例如,从下表中,我应该选择id = 2和id = 3的行。 And after this I have to join the result with table with phrase_id's.
在此之后,我必须将结果与带有template_id的表连接起来。 In my project I use only Ruby and ActiveRecord without Rails.
在我的项目中,我仅使用Ruby和ActiveRecord,而不使用Rails。
+----+---------------------+----------------+--------------+
| id | datetime | foreign_row_id | other_fields |
+----+---------------------+----------------+--------------+
| 1 | 2013-05-02 17:36:15 | 1 | 1 |
| 2 | 2013-05-02 17:36:53 | 1 | 1 |
| 3 | 2013-05-03 00:00:00 | 2 | 3 |
+----+---------------------+----------------+--------------+
Here my ruby code: 这是我的红宝石代码:
@result= Model1.joins(:foreign_row).
where(:user_id => user_id).
order(:datetime).
reverse_order.
select('table1.*, foreign_row.*').
maximum(:datetime, :group => :foreign_row_id).
And it gives me only one record, without grouping by id and joining: {"1":"2013-05-02T17:36:53+09:00"}
. 而且它只给我一个记录,没有按ID分组和加入:
{"1":"2013-05-02T17:36:53+09:00"}
。 What should I change in the my code to get all rows? 我应该更改我的代码以获取所有行吗?
I solved this by parts, first I get a SQL sentence that would solve problem: 我分部分解决了这个问题,首先得到一个可以解决问题的SQL语句:
SELECT * FROM (SELECT * FROM `models` ORDER BY `datetime` desc) m GROUP BY `foreign_row_id`
And then I built that query with Arel: 然后,我使用Arel构建了该查询:
model_table = Model1.arel_table
subquery = model_table.project(Arel.sql('*')).order('`datetime` desc').as('m')
query = model_table.project(Arel.sql('*')).from(subquery).group('`foreign_row_id`')
Finally you can run that query: 最后,您可以运行该查询:
Model1.find_by_sql query.to_sql
I added some back ticks because fields I tested with were SQL reserved words, I think you can omit them. 我添加了一些反勾号,因为我测试过的字段是SQL保留字,我想您可以忽略它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.