最好的方法是在user
模型本身或与user
. 如果您不这样做,则必须始终计算所有用户的总和才能获得他们的评分,这意味着对bets
表进行全表操作。这就是说,这个查询会给你想要的结果,如果超过 1 人的总数相同,它将都算作评分 X:
select id, (select count(h.id) from users u inner join
(select user_id, sum(profitloss) as `total` from bets group by user_id) b2
on b2.user_id = u.id, (select id from users) h inner join
(select user_id, sum(profitloss) as `total` from bets group by user_id) b
on b.user_id = h.id where u.id = 1 and (b.total > b2.total))
as `rating` from users where id = 1;
您将需要插入user.id
查询where id = X
如果您向表中添加一列以user
跟踪其总数,则查询会更简单一些,在此示例中,列名是total_profit_loss
:
select id, total_profit_loss, (select count(h.username)+1 from users u,
(select username, score from users) h
where id = 1 and (h.total_profit_loss > u.total_profit_loss))
as `rating` from users where id = 1;