Home >Database >Mysql Tutorial >How to Retrieve the Latest Visit Time for Each Unique User in Rails with MySQL?
How to Find the Latest Visit of All Distinct Users in Rails with MySQL
You want to retrieve the latest visit time for each distinct user in your database. You're trying to use the DISTINCT ON function in your ActiveRecord query, but you're encountering an SQL syntax error.
The DISTINCT ON function is specific to PostgreSQL, and MySQL doesn't support it. Instead, you can achieve the desired result using the GROUP BY and MAX functions.
Modify your query to the following:
<code class="ruby">Event.group(:user_id).maximum(:time)</code>
This query will group the events by user_id and return the maximum time value for each group. This will give you the latest visit time for each unique user.
Output:
The resulting output will be a hash, where the keys are the user_ids and the values are the latest visit times as Time objects:
<code class="ruby">{ 21 => Tue, 18 Dec 2018 11:15:24 UTC +00:00, 23 => Thu, 20 Dec 2018 06:42:10 UTC +00:00 }</code>
Note that you can use strftime to format the time values to your liking.
The above is the detailed content of How to Retrieve the Latest Visit Time for Each Unique User in Rails with MySQL?. For more information, please follow other related articles on the PHP Chinese website!