代码之家  ›  专栏  ›  技术社区  ›  Matt

SQL-从另一个表更新表-语法错误

  •  0
  • Matt  · 技术社区  · 7 年前

    我有两个SQL表:

    matches (columns are hometeam, awayteam, id, gameweek)
    teams (columns are teamcode, teamname)
    

    matches.hometeam matches.awayteam 由与中的整数相对应的整数组成 teams.teamcode . 我正试着去 更新为从中的相应字符串中提取的字符串 teams.teamname . 如果这是不可能的,那么我需要创建一个新表,如下所述。

    我尝试了下面的代码,但它在倒数第二行产生了语法错误(错误1064(42000))。我不明白为什么。

    UPDATE matches
    SET matches.hometeam = teams.teamname
    FROM matches
    INNER JOIN teams
    ON (matches.hometeam = teams.teamcode);
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Gordon Linoff    7 年前

    错误1064是一个MySQL错误。如果您使用的是MySQL,正确的语法是:

    UPDATE matches m JOIN
           teams t
           ON m.hometeam = t.teamcode
        SET m.hometeam = t.teamname;
    

    然而,这不会真正起作用。您需要做的是添加ID:

    alter table matches add hometeamcode int;
    

    然后做:

    UPDATE matches m JOIN
           teams t
           ON m.hometeam = t.teamcode
        SET m.hometeamcode = t.teamname;
    

    matches 表应具有整数代码,引用中的行 teams .

    您只需编写查询即可获得名称:

    select m.*, th.teamname as hometeamname, ta.teamname as awayteamname
    from matches m join
         team th
         on m.hometeam = th.teamcode join
         team ta
         on a.hometeam = ta.teamcode;
    

    如果你不想做这件事 join