Home > Database > Mysql Tutorial > body text

How to Get the Latest Visits of All Unique Users in MySQL ActiveRecord?

Susan Sarandon
Release: 2024-10-31 01:02:29
Original
529 people have browsed it

How to Get the Latest Visits of All Unique Users in MySQL ActiveRecord?

How to Use the Equivalent of DISTINCT ON in MySQL ActiveRecord

The requirement is to retrieve the latest visits of all distinct users from the events table. Using the DISTINCT ON(user_id) clause with MySQL in ActiveRecord results in a syntax error.

The MySQL equivalent of DISTINCT ON is to use GROUP BY with the MAX() function:

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

This query will group the results by user_id and return the maximum value for the time column for each group. The output will be a hash with the user_id as the key and the latest visit time as the value:

{
  21 => "2018-12-18 09:44:59",
  42 => "2018-12-19 12:08:59"
}
Copy after login

Note: DISTINCT ON(columns) is a PostgreSQL-specific syntax. MySQL does not support this syntax directly.

The above is the detailed content of How to Get the Latest Visits of All Unique Users in MySQL 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
Latest Articles by Author
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!