首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >元素的每种属性组合的投票数最多。

元素的每种属性组合的投票数最多。
EN

Stack Overflow用户
提问于 2020-11-24 16:34:41
回答 1查看 31关注 0票数 0

在我的方案中,用户可以投票给不同的怪物,这些怪物有不同的能力(例如闪电,火)和不同的身体。身体是一种多态的联系,因为它可以来自不同类型的动物。以下是该模式的相关部分:

代码语言:javascript
复制
votes:
monster_id
power_id
body_id #polymorphic association
body_type #polymorphic association

对于每一个在投票表上有代表性的力量和身体的组合,我想找出获得最多选票的怪物。

例如,一个具体的例子:

代码语言:javascript
复制
--------------------------------------------------
| votes                                          |
--------------------------------------------------
| monster_id| power_id | body_id | body_type     |
--------------------------------------------------
| 1         | 1        | 1       | Body::Mammal  |
| 2         | 1        | 1       | Body::Mammal  |
| 2         | 1        | 1       | Body::Mammal  |
| 11        | 2        | 11      | Body::Reptile |
| 11        | 2        | 11      | Body::Reptile |
| 22        | 2        | 11      | Body::Reptile |
--------------------------------------------------

结果我想要:

代码语言:javascript
复制
- ["For the combination (power_id: 1, body_id: 1, body_type: Body::Mammal), the monster with most votes is monster_id: 2",
"For the combination (power_id: 2, body_id: 11, body_type: Body::Reptile), the monster with most votes is monster_id: 11",
...]

我使用的是Rails6和postgres,所以我可以选择使用ActiveRecord,我对此略有偏好,但我意识到这可能需要原始的sql。

我知道答案很可能是这个问题中给出的答案的扩展,在这个问题中,它们用更少的属性做类似的事情,但我似乎不能添加额外的复杂性来容纳更多的列。sql: select most voted items from each user

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-24 18:13:45

如果我没看错的话,你可以使用distinct on和聚合:

代码语言:javascript
复制
select distinct on (body_id, power_id, body_type) 
    body_id, power_id, body_type, monster_id, count(*) cnt_votes
from votes
group by body_id, power_id, body_type, monster_id
order by body_id, power_id, body_type, count(*) desc
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64982841

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档