I'm trying to convert the following SQL Query to something Rails can understand:
SELECT posts.* FROM
(
SELECT group_id, MAX(updated_at) AS updated_at FROM posts WHERE group_id IN (4, 6, 9) GROUP BY group_id
) AS latest_posts
INNER JOIN posts ON
latest_posts.group_id = posts.group_id AND
latest_posts.updated_at = posts.updated_at;
The name of the model is Post
. My attempt:
Post.select("(SELECT group_id, MAX(updated_at) AS updated_at FROM posts WHERE group_id IN (4, 6, 9) GROUP BY group_id) AS latest_posts")
.joins('INNER JOIN posts ON latest_posts.group_id = posts.group_id AND latest_posts.updated_at = posts.updated_at')
The error:
Error:
UserTest#test_feed_should_have_the_right_posts:
ActiveRecord::StatementInvalid: PG::DuplicateAlias: ERROR: table name "posts" specified more than once
test/models/user_test.rb:100:in `block in <class:UserTest>'
Update: Close but no cigar. Frustrating.
irb(main):046:0> Post.select("posts.* FROM (SELECT group_id, MAX(updated_at) AS updated_at FROM posts WHERE group_id IN (4, 6, 9) GROUP BY group_id) AS latest_posts").joins("INNER J
OIN posts ON latest_posts.group_id = posts.group_id AND latest_posts.updated_at = posts.updated_at")
Produces:
SELECT posts.* FROM
(SELECT group_id, MAX(updated_at) AS updated_at FROM posts WHERE group_id IN (4, 6, 9) GROUP BY group_id)
AS latest_posts
FROM "posts"
INNER JOIN posts
ON latest_posts.group_id = posts.group_id AND latest_posts.updated_at = posts.updated_at
Try
Post.select("(SELECT group_id, MAX(updated_at) AS updated_at FROM posts p1 WHERE group_id IN (4, 6, 9) GROUP BY group_id) AS latest_posts")
.joins('INNER JOIN posts p2 ON latest_posts.group_id = p2.group_id AND latest_posts.updated_at = p2.updated_at')
I suspect that by aliasing the two separate references to the "posts" table, then the query will be acceptable to Rails
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.