【问题标题】:how to use DISTINCT ON with mysql using ActiveRecord如何使用 ActiveRecord 将 DISTINCT ON 与 mysql 一起使用
【发布时间】:2019-07-10 01:27:07
【问题描述】:

想要所有不同用户的所有最新访问。

为此,我使用以下查询

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

出现 SQL 语法错误。

ActiveRecord::StatementInvalid (Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ON(user_id) user_id, time FROM `events` ORDER BY `events`.`time` DESC ' at line 1: SELECT  DISTINCT ON(user_id) user_id, time FROM `events` ORDER BY `events`.`time` DESC LIMIT 11)

事件表列名

["id", "visit_id", "user_id", "name", "properties", "time"] 

谁能帮帮我

预期的输出是这样的

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

21 是 user_id,value 是上次访问时间

使用mysql作为数据库

【问题讨论】:

标签: mysql ruby-on-rails activerecord


【解决方案1】:

因此,您希望所有用户访问都具有上次访问时间。

您可以将GROUPMAX 函数一起使用,而不是使用DISTINCT 函数。

查询看起来像

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

这会输出你想要的结果

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

希望这对你有用。

仅供参考 DISTINCT ON(列)。是 PostgreSQL 语法。

【讨论】:

    【解决方案2】:

    就像我在 cmets 中所说的 DISTINCT ON(column), * 是 PostgreSQL SQL 语法。

    下面的查询你需要在 MySQL 中重写

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

    最容易做到这一点的是使用SUBSTRING_INDEX(GROUP_CONCAT(..))
    下面的查询应该会给你正确的结果。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多