【问题标题】:SQL - update table from another table - syntax errorSQL - 从另一个表更新表 - 语法错误
【发布时间】:2019-02-03 10:13:36
【问题描述】:

我有两个 SQL 表:

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

matches.hometeammatches.awayteam 由与teams.teamcode 中的整数对应的整数组成。我试图让matches.hometeammatches.awayteam 更新为从teams.teamname 中的相应字符串中获取的字符串。如果这不可能,那么我需要按照说明创建一个新表。

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

UPDATE matches
SET matches.hometeam = teams.teamname
FROM matches
INNER JOIN teams
ON (matches.hometeam = teams.teamcode);

【问题讨论】:

  • “matches.hometeam ...由整数组成”“正在尝试获取matches.hometeam ...更新为字符串” -您不能将字符串放入整数列
  • 你有外键或主键吗?您是否关心流程结束时的列名?你确定你应该做你正在尝试做的事吗?

标签: sql sql-update


【解决方案1】:

错误 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,那么把逻辑封装在视图中。

【讨论】:

  • 这显示了正确的方法:添加具有正确类型的新列,然后设置其值。新列的名称选择可能是错误的;应该是hometeam_name,对吧?冲洗并为客队重复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-17
  • 2012-12-11
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
  • 2022-01-18
相关资源
最近更新 更多