Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

ruby on rails - how to use DISTINCT ON with mysql using ActiveRecord

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, time')

Getting SQL syntax error.

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)

events table column names

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

can anyone help me out in this

Expected output something like this

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

21 is user_id and value is last visit time

Using mysql as database

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...