1

我必须设置一个 vs 模块,用户可以在其中为 Profile A 或 B 投票。每条记录将存储 3 个重要值:投票的人、获胜的人、失败的人。

用户

  • id_user
  • 姓名

用户对战

  • id_versus - 主键
  • id_user - 投票的人
  • id_user_winner - 显然是赢家
  • id_user_loser - 失败者

我可以通过分别执行这些查询来计算用户的百分比:

  • $wins = 'SELECT COUNT(*) FROM user_versus WHERE id_user_winner = 6';
  • $loses = 'SELECT COUNT(*) FROM user_versus WHERE id_user_loser = 6';
  • $total = $wins + $loses;

所以%wins = $wins / $total

尽管如此,我相信可以将查询优化为一个,然后将其用作报告查询的子查询(这是我真正需要帮助的查询)。报告需要返回:

获胜百分比大于指定用户的获胜百分比的用户列表

我不知道如何从这一点开始。任何提示都会有所帮助。谢谢!

4

1 回答 1

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
于 2013-10-28T21:56:33.097 回答