gpt4 book ai didi

sql - 按列排序数据库查询,然后随机排序

转载 作者:行者123 更新时间:2023-11-29 13:28:12 27 4
gpt4 key购买 nike

假设您有一个具有投票属性的项目模型。这里可能是一些示例数据:

Item, Votes
-----------
Red 4
Blue 5
Black 5
Green 4
Cyan 5
Yellow 4
Orange 4

我想要一个首先按投票排序的范围:

Item, Votes
-----------
Orange 4
Green 4
Yellow 4
Red 4
Blue 5
Black 5
Cyan 5

然后在每个投票队列中随机化:

Item, Votes
-----------
Green 4
Red 4
Orange 4
Yellow 4
Black 5
Blue 5
Cyan 5

然后限制为前两个结果。

我已经试过了:

scope :options, -> { order('random()').order("votes asc").limit 2 }

还有这个:

scope :options, -> { order("votes asc").order('random()').limit 2 }

但两者都没有按预期工作。第一个版本似乎是完全随机的,而第二个版本则完全不是随机的。

最佳答案

根据您的具体需求,您有两种选择。如果您想要完整结果中的前两个(下面突出显示),则第二个解决方案有效。但是,如果您想要每个组的第一行,则需要稍微修改您的查询(如下所示:)


完整结果的第一行:

scope :options, -> { order('votes ASC, random()').limit(2) }

将选择以下行:

Item, Votes
-----------
Green 4 *
Red 4 *
Orange 4
Yellow 4
Black 5
Blue 5
Cyan 5

每组第一行:

scope :options, -> { select('DISTINCT ON (votes) *').order('votes ASC, random()').limit(2) }

将选择以下行:

Item, Votes
-----------
Green 4 *
Red 4
Orange 4
Yellow 4
Black 5 *
Blue 5
Cyan 5

关于sql - 按列排序数据库查询,然后随机排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29656461/

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