模型是Posts,每个帖子都有upvotes:integer。每天创建数百个帖子,我想通过一个查询返回过去30天内每天排名最高的10个帖子。 (300个结果)
按时间顺序排列
我想返回过去30天的结果,并在同一查询中显示每天的前10条帖子。
预期结果应该是:
[今天的前10个帖子,昨天的前10个帖子... 30天前的前10个帖子。
是否有任何方法可以执行此查询而无需每天进行循环和单独查询?
您可以使用单个查询来获取所有这些查询:
(SELECT * FROM posts WHERE created_at::DATE = CURRENT_DATE ORDER BY upvotes DESC LIMIT 10)
UNION ALL
(SELECT * FROM posts WHERE created_at::DATE = CURRENT_DATE - INTERVAL '1 DAY' ORDER BY upvotes DESC LIMIT 10)
UNION ALL
(SELECT * FROM posts WHERE created_at::DATE = CURRENT_DATE - INTERVAL '30 DAYS' ORDER BY upvotes DESC LIMIT 10)
或三个单个:
Post.where('created_at::date = ?', Date.today).order(upvotes: :desc).limit(10)
Post.where('created_at::date = ?', Date.yesterday).order(upvotes: :desc).limit(10)
Post.where('created_at::date = ?', 30.days.ago).order(upvotes: :desc).limit(10)
SELECT (array_agg('id => ' || id || ', ' || 'body => ' || body || ', ' || 'upvotes => ' || upvotes order by upvotes desc))[1:10] AS posts, date FROM posts GROUP BY date;
它返回具有2个值的散列,第一个是具有包含帖子数组的关键帖子,第二个值是日期
sql = "select (array_agg('id => ' || id || ', ' || 'body => ' || body || ', ' || 'upvotes => ' || upvotes order by upvotes desc))[1:
10] as posts, date from posts group by date;"
records = ActiveRecord::Base.connection.execute(sql)
records[0] = {"posts"=> "{\"id => 8, body => atis atis animatis, upvotes => 9\",\"id => 11, body => Fuga enim sit aliquam., upvotes => 8\",\"id => 20, body => Vel vero fugiat explicabo., upvotes => 8\",\"id => 18, body => Nesciunt dolor voluptatibus ad., upvotes => 7\",\"id => 17, body => Laboriosam qui nam esse., upvotes => 6\",\"id => 13, body => Earum est temporibus odio., upvotes => 6\",\"id => 16, body => Autem qui nam omnis., upvotes => 4\",\"id => 7, body => Facilis aut non aut., upvotes => 4\",\"id => 15, body => Voluptatem non asperiores vero., upvotes => 4\",\"id => 12, body => Nihil facere aut natus., upvotes => 3\"}",
"date"=>2019-11-24 14:41:34 UTC}
然后您可以解析结果。希望对您有所帮助