子查询格式问题

时间:2013-01-01 14:18:19

标签: php mysql subquery

我无法为子查询获取正确的格式。

我的一个查询显示以下内容:

这涉及调用三个表(Ind Stats表,拉动游戏统计数据和团队名称)。如您所见,此查询可以正常工作。

我遇到的麻烦是如何拉动每个在该特定游戏中拥有DD的玩家。玩家是数据库中的另一个能力。我可以理解的是,我应该需要一个子查询,但子查询不是我的强项。

这是我的代码

  SELECT * FROM 

        (SELECT game_Date, 
        game_GameID,
        game_SeasonID,
        game_TeamCode,
        teams_Name,
        stats1_GameID,
        Sum(stats1_DD) AS 'TotGameDD'

        FROM game INNER JOIN teams INNER JOIN stats1
        ON 
        teams_TeamCode = game_TeamCode
        AND
        game_GameID = stats1_GameID

        GROUP BY game_GameID
        HAVING Sum(stats1_DD) >1
        ORDER BY Sum(stats1_DD) desc) t

    INNER JOIN  players INNER JOIN stats1 INNER JOIN game 
    ON stats1_GameID = game_GameID
            AND
    sstorm_rawstats1.stats1_PlayerID = sstorm_players.player_PlayerID

所以,要清楚,这很好用:

  SELECT game_Date, 
    game_GameID,
    game_SeasonID,
    game_TeamCode,
    teams_Name,
    stats1_GameID,
    Sum(stats1_DD) AS 'TotGameDD'

    FROM game INNER JOIN teams INNER JOIN stats1
    ON 
    teams_TeamCode = game_TeamCode
    AND
    game_GameID = stats1_GameID

    GROUP BY game_GameID
    HAVING Sum(stats1_DD) >1
    ORDER BY Sum(stats1_DD) desc

我只是想在这里显示记录DD的玩家的名字。我现在得到这个名字,但它正在计算玩家所玩的所有游戏。我现在很接近。

enter image description here

更新:我现在可以在表格中显示结果,但它只显示一个获得DD的玩家。我想我需要一个循环来显示所有拥有DD的用户。任何帮助,非常感谢。

enter image description here

我刚刚通过在FROM语句中添加GROUP BY stats1_DD和另一个AND来改变我的上述代码:

  FROM game INNER JOIN teams INNER JOIN stats1
    ON 
    teams_TeamCode = game_TeamCode
    AND
    game_GameID = stats1_GameID
    AND
    game_PlayerID = player_PlayerID


    GROUP BY game_GameID, stats1_DD
    HAVING Sum(stats1_DD) >1
    ORDER BY Sum(stats1_DD) desc

1 个答案:

答案 0 :(得分:0)

您应该使用来自您已有查询的结果集或第三个表直接在目标列DD上加入第三个表。类似的东西:

SELECT * 
FROM YourCrrentQuery t
INNER JOIN ThePlayersTable p ON p.DD = t.DD;

SELECT * 
FROM YourCrrentQuery t
WHERE DD IN (SELECT DD 
             FROM ThePlayersTable 
             WHERE DD IS NOT NULL);

更新:您需要使用JOIN表格Players子查询,如下所示:

SELECT * 
FROM 
(
   SELECT 
     game_Date, 
     game_GameID,
     game_SeasonID,
     game_TeamCode,
     teams_Name,
     stats1_GameID,
     Sum(stats1_DD) AS 'TotGameDD'
     FROM game 
     INNER JOIN teams 
     INNER JOIN stats1  ON teams_TeamCode = game_TeamCode
                       AND game_GameID    = stats1_GameID
     GROUP BY game_GameID
     HAVING Sum(stats1_DD) >1
) t
INNER JOIN players p ON t.TotGameDD = p.DD
ORDER BY t.TotGameDD desc;