gpt4 book ai didi

sql - Rails 按关联计数排序

转载 作者:数据小太阳 更新时间:2023-10-29 09:03:26 25 4
gpt4 key购买 nike

我有 2 个模型。 Gif,GifStatistic

gif has_many :gif_statistics

GifStatistics 具有名为 state 的列。它可以是喜欢不喜欢

我想要实现的是查询 gif,但将它们按最高点赞数

排序

类似的东西(伪代码)

Gif.joins(:gif_statistics).order(count(gif.gif_statistics.state))

我如何实现这一目标?

最佳答案

试试这个查询。

Gif.joins(:gif_statistics).select("*, count(gif_statistics.state) as state_count").order("state_count desc")

我个人的建议是您在 gif 模型中创建两个新字段,以便您可以在创建时存储喜欢和不喜欢的计数,这样您就不必执行如此复杂的查询。放置计数器缓存可以提高速度。

关于sql - Rails 按关联计数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29749432/

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