在我的方案中,用户可以投票给不同的怪物,这些怪物有不同的能力(例如闪电,火)和不同的身体。身体是一种多态的联系,因为它可以来自不同类型的动物。以下是该模式的相关部分:
votes:
monster_id
power_id
body_id #polymorphic association
body_type #polymorphic association对于每一个在投票表上有代表性的力量和身体的组合,我想找出获得最多选票的怪物。
例如,一个具体的例子:
--------------------------------------------------
| 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 |
--------------------------------------------------结果我想要:
- ["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
发布于 2020-11-24 18:13:45
如果我没看错的话,你可以使用distinct on和聚合:
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(*) deschttps://stackoverflow.com/questions/64982841
复制相似问题