how to use DISTINCT ON with mysql using ActiveRecord

前端 未结 2 1774
一向
一向 2020-12-02 03:23

Want all the latest visit of all the distinct user.

For this I am using below query

Event.order(time: :desc).select(\'DISTINCT ON(user_id) user_id,          


        
相关标签:
2条回答
  • 2020-12-02 03:43

    So you want all user visits with last visited time.

    Instead of use DISTINCT function, you can use GROUP with MAX function.

    Query looks like

    Events.group(:user_id).maximum(:time)
    

    This Outputs your desired results

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

    Hope this works for you.

    FYI DISTINCT ON(columns). is PostgreSQL Syntax.

    0 讨论(0)
  • 2020-12-02 03:46

    Like i said in the comments DISTINCT ON(column), * is PostgreSQL SQL syntax.

    The query below you need to have to rewrite in MySQL

    SELECT 
     DISTINCT ON(user_id) AS user_id, time
    FROM 
     <table>
    ORDER BY 
     time DESC
    LIMIT 11 
    

    The most easy to do that is using SUBSTRING_INDEX(GROUP_CONCAT(..)).
    The queries below should give you the correct results.

    SET SESSION group_concat_max_len = @@max_allowed_packet;
    
    SELECT 
       user_id
     , SUBSTRING_INDEX(
         GROUP_CONCAT(time
                      ORDER BY
                         time DESC
         )
         , ','
         , 1
     ) AS time
    FROM 
     <table>
    GROUP BY 
     user_id
    ORDER BY 
     time DESC
    LIMIT 11
    
    0 讨论(0)
提交回复
热议问题