Home > Database > Mysql Tutorial > body text

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

DDD
Release: 2024-10-27 20:59:30
Original
663 people have browsed it

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>
Copy after login

Output:

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!