我有三张桌子,State,City和Village。
State (PK_Id,Name,Year)
City (PK_Id,Name,FK_StateId)
Village (PK_Id,Name,Year,FK_CityId)
PK表示主键,FK表示外键。我想把去年的每个州复制到新的一年,去年的每个城市,以及去年的每个村庄。
有可能吗?我该怎么做?它真的比它看起来更难。
更新: 当我想将去年的城市复制到新的一年时,问题出现了。当我决定将去年的村庄复制到新的一年时,似乎真的不可能。
答案 0 :(得分:1)
INSERT INTO State (Name, Year)
SELECT S.Name, 2011
FROM State S
WHERE S.Year = 2010
INSERT INTO City (Name, FK_StateId)
SELECT C.Name, S_new.PK_Id
FROM City C
INNER JOIN State S_old ON C.FK_StateId = S_old.PK_Id
AND S_old.Year = 2010
INNER JOIN State S_new ON S_old.Name = S_new.Name
AND S_new.Year = 2011
INSERT INTO Village (Name, Year, FK_CityId)
SELECT V.Name, 2011, C_new.PK_Id
FROM Village V
INNER JOIN City C_old ON C.FK_CityId = C_old.PK_Id
AND C_old.Year = 2010
INNER JOIN City C_new ON C_old.Name = C_new.Name
AND C_new.Year = 2011
答案 1 :(得分:-1)
您可以使用临时表来存储3个表的副本。更新所有临时表中的年份,然后插回主表。