MySQL:在YEAR(日期)加入子查询

时间:2018-11-20 23:44:25

标签: mysql

尝试创建一个表,该表汇总另一个表中的数据。摘要应按年从日期字段中提取。当我尝试通过子查询将新字段包括到表中时,在ON子句中出现1054(未知列)错误。我尝试加入date并收到相同的错误。

CREATE TABLE IF NOT EXISTS park_factor (
SELECT YEAR(games.date) AS year
    , games.home_team
    , sum(games.runs0) AS ht_runs
    , sum(games.runs1) as away_runs
    , round(leagues.rules_schedule_games_per_team/2,0) AS home_games
    , x.home_losses
FROM games 
    INNER JOIN leagues ON games.league_id=leagues.league_id
    INNER JOIN (
      SELECT YEAR(games.date) as year
          , games.home_team
          , COUNT(*) as home_losses
      FROM games
      WHERE games.runs1>runs0
      GROUP BY year, games.home_team
      ) AS x ON x.year=games.year AND x.home_team=games.home_team
GROUP BY year, games.home_team, home_games, home_losses );

2 个答案:

答案 0 :(得分:0)

没有games.year列,这就是导致您出错的原因。您需要JOIN使用

 x.year = YEAR(games.date) AND x.home_team=games.home_team

答案 1 :(得分:0)

在@Nick回答时我弄清楚了。有效的代码是:

CREATE TABLE IF NOT EXISTS park_factor (
SELECT YEAR(games.date) AS `year`
    , games.home_team
    , sum(games.runs0) AS ht_runs
    , sum(games.runs1) as away_runs
    , round(leagues.rules_schedule_games_per_team/2,0) AS home_games
    , x.home_losses
FROM games 
    INNER JOIN leagues ON games.league_id=leagues.league_id
    INNER JOIN (
      SELECT YEAR(games.date) as `year`
          , games.home_team
          , COUNT(*) as home_losses
      FROM games
      WHERE games.runs1>runs0
      GROUP BY year, games.home_team
      ) AS x ON x.`year`=YEAR(games.date) AND x.home_team=games.home_team
GROUP BY YEAR(games.date), games.home_team, home_games, home_losses );