将JOIN添加到嵌套在MySQL中选择

时间:2015-07-27 16:04:12

标签: mysql

对于下面的查询,我希望能够在最终结果中显示在嵌套选择中选择的每个玩家的完整玩家名称。我知道如何连接相应的字段:CONCAT (nameFirst, ' ', nameLAST) AS 'playerName'以及将其放在第一个SELECT中的位置。 nameFirst和nameLast都在Master表中。关键字段playerID在Batting和Master表中。我不知道的是我需要添加到下面的查询中,以获得每个在特定赛季击中最多本垒打的Met的全名。

SELECT b.*
FROM Batting b JOIN
     (SELECT yearID, teamID, MAX(HR) as maxHR
      FROM Batting
      WHERE teamID = 'NYN'
      GROUP BY yearID, teamId
     ) bb
     ON bb.yearId = b.yearId and bb.teamId = b.teamId and bb.maxHR = b.HR;

1 个答案:

答案 0 :(得分:0)

联接应该是INNER JOIN,以确保您只选择具有max(HR)的记录 - 如果有多个玩家具有相同的最大值(HR),则两者都会出现。那么你应该LEFT JOIN主表来获取玩家的名字:

SELECT b.*, CONCAT (m.nameFirst, ' ', m.nameLAST)
  FROM Batting b 
  INNER JOIN
     (SELECT yearID, teamID, MAX(HR) as maxHR
        FROM Batting
        WHERE b.teamID = 'NYN'
       GROUP BY yearID, teamId
     ) bb
    ON bb.yearId = b.yearId 
       and bb.teamId = b.teamId 
       and bb.maxHR = b.HR
   LEFT JOIN Master m
    ON b.playerID = m.playerID
   ORDER BY b.yearID desc;