2013-04-03 72 views
0

我需要你的幫助:的MySQL如何使用變量的值的查詢在自己的子查詢

我有一組爲用戶設置,遊戲和結果的關係表中,我試圖來計算每個用戶贏取百分比。

由於很多瀏覽我發現了以下方法:

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; 

這完全適用於獲得約翰斯%,但我希望它掃描整個表的結果和打印值的每一個人。不過,我不允許使用:

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在執行時如何獲得傳遞給子查詢的值?

+0

請張貼結構(結果表中的重要列) –

+0

結果表最多 – user2240912

+0

有一個球員表?如果是這樣,你可以分享它的模式嗎? – DiscoInfiltrator

回答

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; 

的UNION在FROM子句中正在建設,我可以用它來加入遊戲用戶列表(找到每個玩家的遊戲總數)和獲獎者(找到每個玩家勝場數)。

COALESCE用於玩家沒有贏得任何遊戲的情況。由於我們正在連接表,這允許我們在沒有匹配時默認爲0而不是NULL。

這裏的一個基於sqlfiddle出了關於您的模式假設:

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

+0

謝謝你的倉促答覆,但它沒有工作=在'條款'上的未知列'games.Player_1' – user2240912

+0

我剛剛做了一個編輯。請讓我知道這對你有沒有用。 – DiscoInfiltrator

+0

再次感謝您的回覆,它沒有工作='where子句'中的Unknown.column'結果.Winner' – user2240912