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:
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!