gpt4 book ai didi

mysql - 如何使用 ActiveRecord 将 DISTINCT ON 与 mysql 一起使用

转载 作者:行者123 更新时间:2023-11-29 06:35:55 25 4
gpt4 key购买 nike

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

为此,我使用以下查询

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作为数据库

最佳答案

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

您可以将 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}

希望这对您有用。

仅供引用区别于(列)。是 PostgreSQL 语法。

关于mysql - 如何使用 ActiveRecord 将 DISTINCT ON 与 mysql 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53868870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com