【问题标题】:Finding the most recent entry per reference (foreign key) in Rails在 Rails 中查找每个引用(外键)的最新条目
【发布时间】:2013-04-26 05:57:11
【问题描述】:

无法完全弄清楚这一点。我有一张这样的桌子

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 有关,但我从来没有很好地掌握这些查询。

【问题讨论】:

    标签: sql ruby-on-rails activerecord group-by


    【解决方案1】:

    试试这个:

    select user_id,MAX(time) as MaxTime from tableName Group by user_id
    

    【讨论】:

      【解决方案2】:

      使用以下查询:

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

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2019-03-24
        • 2020-03-10
        • 2017-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-18
        • 1970-01-01
        相关资源
        最近更新 更多