如何使用ActiveRecord在MySQL上使用DISTINCT ON

问题描述 投票:0回答:2

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

为此,我正在使用以下查询

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,值是上次访问时间

使用mysql作为数据库

想要所有不同用户的所有最新访问。为此,我正在使用以下查询Event.order(time::desc).select('DISTINCT ON(user_id)user_id,time')获取SQL语法错误。 ActiveRecord :: ...

mysql ruby-on-rails activerecord
2个回答
1
投票

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


1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.