我必须设置一个对比模块,用户可以投票选择个人资料A或B.每个记录将存储3个重要值:投票人,获胜者,失去者。
用户
user_versus
我可以通过单独执行这些查询来计算用户的百分比:
所以%wins = $ wins / $ total
但是,我相信查询可以优化为一个,然后将其用作报表查询的子查询(这是我实际需要帮助的那个)。报告需要返回:
获胜百分比大于指定用户的赢率百分比的用户列表
我不知道如何从这一点开始。任何提示都会有帮助。谢谢!
答案 0 :(得分:2)
对于一位用户:
SELECT ifnull(wins, 0) wins, ifnull(loses,0) loses,
ifnull(wins, 0)+ifnull(loses,0) total,
ifnull(wins, 0) / ( ifnull(wins, 0)+ifnull(loses,0)) percent
FROM (
SELECT
(SELECT COUNT(*) FROM user_versus WHERE id_user_winner = 6 ) wins,
(SELECT COUNT(*) FROM user_versus WHERE id_user_loser = 6 ) loses
) subqry
对于所有用户:
SELECT id_user_winner AS id_user,
ifnull(wins, 0) wins
ifnull(loses,0) loses
ifnull(wins, 0)+ifnull(loses,0) total,
ifnull(wins, 0) / ( ifnull(wins, 0)+ifnull(loses,0)) percent
FROM (
SELECT id_user_winner AS id_user FROM user_versus
UNION
SELECT id_user_loser FROM user_versus
) u
LEFT JOIN
FROM (
SELECT id_user_winner, count(*) wins
FROM user_versus
GROUP BY id_user_winner
) w
ON u.id_user = id_user_winner
LEFT JOIN (
SELECT id_user_loser, count(*) loses
FROM user_versus
GROUP BY id_user_loser
) l
ON u.id_user = l.id_user_loser