1

完全想不通这个。我有一张这样的桌子

user_id | time       |
----------------------
1       | 10         |
1       | 11         |
1       | 12         |
2       | 13         |
3       | 14         |

它不仅如此,而且time是一个日期时间字段,但该信息应该是无关紧要的。我只想提取每个用户的最新记录。所以我的结果集看起来像

user_id | time       |
----------------------
1       | 12         |
2       | 13         |
3       | 14         |

我将如何使用 Rails ActiveRecord 接口来做到这一点?我假设它与 GROUP BY 有关,但我从来没有很好地掌握这些查询。

4

2 回答 2

1

尝试这个 :

select user_id,MAX(time) as MaxTime from tableName Group by user_id
于 2013-04-26T06:13:27.870 回答
0

使用以下查询:

select user_id,time from tableName where user_id=(select last(user_id) from tableName) group by user_id

希望它有帮助。

于 2013-04-26T06:03:24.063 回答