Home  >  Article  >  Database  >  How to Get the Latest Visit Time for Each User in MySQL Using ActiveRecord?

How to Get the Latest Visit Time for Each User in MySQL Using ActiveRecord?

DDD
DDDOriginal
2024-10-27 20:59:30731browse

How to Get the Latest Visit Time for Each User in MySQL Using ActiveRecord?

Using DISTINCT ON with MySQL Using ActiveRecord

To retrieve the latest visit time for each distinct user using MySQL, the syntax for DISTINCT ON is not supported. Instead, you can utilize the GROUP BY and MAX functions.

Query and Results:

<code class="ruby">Events.group(:user_id).maximum(:time)</code>

Output:

{21=>Tue, 18 Dec 2018 11:15:24 UTC +00:00, 23=>Thu, 20 Dec 2018 06:42:10 UTC +00:00}

Explanation:

  • GROUP BY groups the results by user_id.
  • MAX selects the maximum value (latest time) for each group.

This query achieves the expected output of a dictionary where each user ID corresponds to their last visit time.

The above is the detailed content of How to Get the Latest Visit Time for Each User in MySQL Using ActiveRecord?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn