Sql 建立一种基于post计数和频率的趋势分析算法
假设我有一个董事会模型。董事会有很多职位。我只是想找到在(x)天内拥有最高帖子数量的董事会。下面是我对这件事的非常天真的态度。根据提供的代码,我得到了错误:Sql 建立一种基于post计数和频率的趋势分析算法,sql,ruby-on-rails,postgresql,Sql,Ruby On Rails,Postgresql,假设我有一个董事会模型。董事会有很多职位。我只是想找到在(x)天内拥有最高帖子数量的董事会。下面是我对这件事的非常天真的态度。根据提供的代码,我得到了错误: ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: missing FROM-clause entry for table "posts") LINE 1: SELECT "boards".* FROM "boards" WHERE (board.posts.create
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: missing FROM-clause entry for table "posts")
LINE 1: SELECT "boards".* FROM "boards" WHERE (board.posts.created_...
^
: SELECT "boards".* FROM "boards" WHERE (board.posts.created_at >= '2019-06-05 12:14:30.661233') LIMIT $1
请让我知道,除了我收到的错误之外,是否还有更好的方法
class Board < ApplicationRecord
has_many :posts
scope :trending, -> { includes(:posts).where('board.posts.created_at >= ?', Time.now-7.days).order(posts_count: :desc) }
end
class Post < ApplicationRecord
belongs_to :board, counter_cache: true
end
更新:
Board.joins(:posts)
.select("boards.*, count(posts.id) as latest_posts_count")
.where('posts.created_at >= ?', 7.days.ago)
.order('latest_posts_count desc')
.group('boards.id')
试试这个,你需要加入它并按board\u id
Board.joins(:posts)
.select("boards.*, count(posts.id) as posts_count")
.where('posts.created_at >= ?', 7.days.ago)
.order('posts_count desc')
.group('boards.id')
说明:
- 我们连接了(内部连接)表,因此默认情况下,您只能获得至少有一个post与之关联的板
- 我们是根据邮件数量订购的
- 我们根据boards.id对它们进行分组
ActiveRecord::StatementInvalid(PG::AmbiguousColumn:error:ORDER BY“posts\u count”不明确)第1行:…2:40:52.315019')GROUP BY posts.board\u id ORDER BY posts\u Councon…
好的,我的错,你已经在使用计数器缓存了。更新解决方案检查更新,此处不能使用计数器缓存列。原因是您在posts_count中有所有相关的posts计数,但您需要根据最近7天的posts计数来确定工作范围。因此,通过更新的查询,我得到了以下错误:ActiveRecord::StatementInvalid(PG::GroupingError:error:column“boards.id”必须出现在GROUP BY子句中或用于聚合函数)第1行:SELECT boards.*,将(posts.id)计数为上次更新的查询中的一次更改。通过使用计数器缓存,您可以获得所有的帖子计数,而不是最新的帖子。你说得对!谢谢你指出这一点。
Board.joins(:posts)
.select("boards.*, count(posts.id) as posts_count")
.where('posts.created_at >= ?', 7.days.ago)
.order('posts_count desc')
.group('boards.id')