我有两张桌子:
小组
Id Name
1 Manchester
2 Arsenal
3 Inter
4 Milan
游戏
GameId FirstTeamId GoalsFirstTeam GoalsSecondTeam SecondTeamId
1 1 0 0 2
2 3 2 3 4
3 1 1 1 3
我希望使用select GameResult
更新为Games
并加入两个表Teams
和GameId FirstTeam GoalsFT GoalsST SecondTeam
1 Manchester 0 0 Arsenal
2 Inter 2 3 Milan
3 Manchester 1 1 Inter
,如下所示:
UPDATE GameResult
SET GameId = (SELECT GameId
FROM Games),
FirstTeam = (SELECT t1.Name AS FirstTeam
FROM Games AS g
INNER JOIN Teams t1
ON g.FirstTeamId = t1.Id),
GoalsFT = (SELECT GoalsFirstTeam
FROM Games),
GoalsST = (SELECT GoalsSecondTeam
FROM Games),
SecondTeam = (SELECT t2.Name AS SecondTeam
FROM Games AS g
INNER JOIN Teams t2
ON g.SecondTeamId = t2.Id)
我试过了:
{{1}}
......但它没有用。
有人可以帮我这个吗?
答案 0 :(得分:1)
试试这个
UPDATE GameResult
SET GameId = G.GameId,
FirstTeam = T1.Name,
GoalsFT = G.GoalsFirstTeam,
GoalsST = G.GoalsSecondTeam,
SecondTeam = T2.Name
FROM Games G INNER JOIN Teams T1 ON G.FirstTeamID=T1.ID
INNER JOIN Teams T2 ON G.SecondTeamId=T2.ID
<强>更新强>
如果您只想从其他2个表中将新记录插入到GameResult中,请尝试使用
INSERT GameResult (GameId, FirstTeam, GoalsFT, GoalsST, SecondTeam)
SELECT G.GameId, T1.Name, G.GoalsFirstTeam, G.GoalsSecondTeam, T2.Name
FROM Games G INNER JOIN Teams T1 ON G.FirstTeamID=T1.ID
INNER JOIN Teams T2 ON G.SecondTeamId=T2.ID
答案 1 :(得分:0)
您的桌子'GameResult'似乎没有任何记录需要更新。首先填写它,然后使用Pupa Rebbe的上述解决方案,或使用Merge
语句插入,更新和(如果需要)删除记录。
有关详细信息,请参阅this MS library
答案 2 :(得分:0)
简单的解决方案:
从GameResult删除 走 插入GameResult(GameId, FirstTeam,GoalsFT,GoalsST,SecondTeam) SELECT g.GameId, t1.Name AS FirstTeam, g.GoalsFirstTeam,g.GoalsSecondTeam, t2.Name AS SecondTeam 来自游戏g INNER JOIN Team t1 ON g.FirstTeamId = t1.Id INNER JOIN Team t2 ON g.SecondTeamId = t2.Id