title: MySQL Stored procedure says alias is undefined in select statement
body: <p>I have the following statement, which produces this error. Apparently the alias "R" in the first line of the select statement is not declared, but it's right there at the end of the statement. Anyone have any ideas?</p>
  
  <p><strong>#1327 - Undeclared variable: R</strong> </p>
  
  <pre><code>    CREATE PROCEDURE `get_series_completion`(IN team1_id INT, IN team2_id INT, IN round_shortname VARCHAR(5))
  BEGIN
      DECLARE num_games_total, num_games_played INT;
  
      SELECT COUNT(*) INTO num_games_played, R.games_per_series INTO num_games_total
      FROM (
          SELECT game_id
          FROM team_games
          WHERE team_id IN (team1_id, team2_id)
          GROUP BY game_id
              HAVING COUNT(*) = 2
              AND SUM(standing = 0) = 0
      ) AS S, rounds AS R ON R.round_shortname = round_shortname;
  
      SELECT num_games_played/num_games_total;
  END$$
  </code></pre>