我有两个SQL表:
matches (columns are hometeam, awayteam, id, gameweek)
teams (columns are teamcode, teamname)
matches.hometeam
和matches.awayteam
包括对应于整数中teams.teamcode
整数。我试图让matches.hometeam
和matches.awayteam
更新到从在teams.teamname
对应的字符串采取字符串。如果这是不可能的,那么我需要为所描述的创建一个新表。
我曾尝试下面的代码,但它在倒数第二的两行(错误1064(42000))产生语法错误。我想不通为什么。
UPDATE matches
SET matches.hometeam = teams.teamname
FROM matches
INNER JOIN teams
ON (matches.hometeam = teams.teamcode);
错误1064是一个MySQL错误。如果你正在使用MySQL,正确的语法是:
UPDATE matches m JOIN
teams t
ON m.hometeam = t.teamcode
SET m.hometeam = t.teamname;
然而,这并不会真正发挥作用。你需要做的是添加标识:
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
,然后封装在视图中的逻辑。