Mysql树表连接和计数行

时间:2013-03-13 09:13:49

标签: mysql

我有以下三个表格。我想使用MySQL查询加入他们。在表格下方,我还提供了输出的样子。

GameTable

GameID  GameName    
1       NvsA
2       NvsB
3       DvsA
4       NvsE

PlayerOnGame

GameID  PlayerName  PlayerNumber  PlayerID
1       Clement     7             10
1       Niyoyita    8             11
2       Clement     8             10
2       David       6             5

PlayerdataTable

GameID  Action  PlayerNumber
1       kick    7
1       pass    8
1       Run     7
1       Kick    7
2       Kick    8
2       Pass    6
2       Run     8
2       Run     8

仅输出PlayerName = Clement

GameName  Action  ActionCount
NvsA      Kick    2
NvsA      Run     1
NvsB      Kick    1
NvsB      Run     2

请有人帮我查询以获得此输出吗?

1 个答案:

答案 0 :(得分:1)

您可以使用此查询来计算

SELECT
    gt.GameName,
    pdt.Action,
    count(pdt.Action) AS ActionCount
FROM GameTable AS gt
INNER JOIN PlayerdataTable AS pdt ON pdt.GameID = gt.GameID
INNER JOIN PlayerOnGame AS pg ON pg.GameID = pdt.GameID AND pg.PlayerNumber = pdt.PlayerNumber
WHERE pg.PlayerName = 'Clement'
GROUP BY gt.GameID , pdt.Action