SQL Update 1表,包含来自其他两个的数据

时间:2015-08-28 18:36:04

标签: sql sql-update dml

好的,我有3张桌子。第一个是建筑表。

buildingid | buildingcode  | buildingname | level | building_hp | upkeep |
88        |    bdg ojy     |  orbital js  |    3  |    1800     |  48000 |
89        |    bdg ojy     |  orbital js  |    4  |    2100     |  56000 |
90        |    bdg ojy     |  orbital js  |    5  |    2400     |  64000 |

第二个是buildingsprime表。

id | planetcode |buildingcode| buildingname | level | buildingid | planetname
1  |    p1      |   bdg ojy  |   orbital js |   3   |    88      |   Tikinov

第三个是planetsprime表,其中填充了来自其他两个表的数据。

buildingid | planetname | buildingname | level | building _hp | upkeep
  88       |  Tikinov   |  orbital js  |  3    |  1800        |  48000

所以我需要做的是能够更改buildingsprime表上的Levels,并使用与构建表中的级别对应的buildingid更新buildingsprime表和planetsprime表中的buildingid。完成后,planetsprime表列数据将根据建筑物和建筑物表格的等级统计数据进行更新。示例:如果我们将buildingprime表中的级别从3更改为4,那么88的buildingid将更新为89. planetprime还会将level和buildingid以及building_hp和upkeep更新为建筑物表中的89对应。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

这些工作吗?

update buildingsprime
set buildingid = (
    select b.buildingid
    from building b
    where b.buildingcode = buildingsprime.buildingcode and b.level = buildingsprime.level
)
where id = ?

update planetsprime
set building_hp = (
    select b.building_hp
    from buildingsprime bp inner join bulidings b on b.buildingid = bp.buildingid
    where bp.buildingid = planetsprime.buildingid
)
where id = ?

答案 1 :(得分:0)

您可以在" buildingsprime"上使用触发器("代替"或""")当您更新Level Column值以更新" buildingID"在buildingsprime中更新" planetsprime"表

CREATE TRIGGER trigger_buildingsprime on buildingsprime
instead of update 
as
begin

declare @level int,
        @oldlevel int,
        @buildind_hp int,
        @buildingid int
--select current level id
select @level= level from inserted
--select the level id being updated
select @oldlevel = level from deleted

-- select the building_hp and buildingid for the new level
select @building_hp = b.building_hp, @buildingid = b.buildingid from building b 
where b.level = @level

--update building prime to set the update building id for the new level
update buildingsprime set level = @level, @building_hp =@building_hp

--update the planetsprime table with new level details where the level id = old level
update planetsprime level = @level, @building_hp =@building_hp, buildingid = @buildingid 
where level= @oldlevel

end

希望这有帮助