MySQL如何在自己的子查询中使用Query中的变量值

时间:2013-04-03 14:50:00

标签: mysql percentage

我需要你的帮助:

我为用户,游戏和结果设置了一组关系表,我正在尝试计算每个用户赢得百分比。

感谢大量浏览,我发现了以下方法:

SELECT Winner, (COUNT(Winner) * games.TotalPlayed) AS PercentWon
FROM Results
JOIN (
  SELECT 100/COUNT(*) AS TotalPlayed
  FROM games
  where Player_1 = 'John' OR Player_2 = 'John'
) AS games

where Winner == 'John' 
GROUP BY Winner
ORDER BY PercentWon DESC;

这对于获得Johns%非常有效,但我希望它能够扫描整个Results表并为每个人打印值。但是,我不允许使用:

SELECT Winner, (COUNT(Winner) * games.TotalPlayed) AS PercentWon
FROM Results
JOIN (
  SELECT 100/COUNT(*) AS TotalPlayed
  FROM games
  where Player_1 = Winner OR Player_2 = Winner
) AS games

where Winner != 'Draw' 
GROUP BY Winner
ORDER BY PercentWon DESC;

因为没有定义Winner。如何在执行子查询时将Winner的值传递给子查询?

1 个答案:

答案 0 :(得分:0)

我终于想出了一些对你有用的东西。这很棘手,因为玩家可以在games表中的两个字段之一。

SELECT player, (COALESCE(totalWon, 0) / count(*) * 100) as PercentWon
FROM ((SELECT DISTINCT Player_1 as player FROM games) UNION (SELECT DISTINCT Player_2 as player FROM games)) players
INNER JOIN games on (games.Player_1 = player or games.Player_2=player)
LEFT JOIN
(
    SELECT Winner, COUNT(Winner) as totalWon
    FROM Results
    WHERE Winner != 'Draw' 
    GROUP BY Winner
) as winners
ON winners.Winner = player
GROUP BY player
ORDER BY PercentWon DESC;

FROM子句中的UNION正在构建一个用户列表,我可以用它来加入游戏(找到每个玩家的游戏总数)和获胜者(找到每个玩家的获胜次数)。

COALESCE用于玩家未赢得任何游戏的情况。由于我们正在连接表,因此当没有匹配时,这允许我们默认为0而不是NULL。

根据我对您的架构的假设,这是一个sqlfiddle:

http://sqlfiddle.com/#!2/d762c/1/0