SQL使用其他两个表中的数据更新1表

SQL使用其他两个表中的数据更新1表,sql,sql-update,dml,Sql,Sql Update,Dml,好的,我有三张桌子。第一个是建筑表 buildingid | buildingcode | buildingname | level | building_hp | upkeep | 88 | bdg ojy | orbital js | 3 | 1800 | 48000 | 89 | bdg ojy | orbital js | 4 | 2100 | 56000 | 90

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

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
因此,我需要做的是能够更改BuildingPrime表中的级别,并让它使用与BuildingPrime表中的级别对应的buildingid更新BuildingPrime表和planetsprime表中的buildingid。完成后,planetsprime表列数据将根据建筑物和BuildingPrime表中的标高统计数据进行更新。示例:如果我们将buildingprime表中的级别从3更改为4,则buildingid 88将更新为89。PlanetTime还将更新标高和buildingid以及building_hp和维护,使其与buildings表中的89对应。有什么建议吗?

这些有用吗

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 = ?
当您更新级别列值以更新BuildingPrime中的“buildingID”并更新“planetsprime”表时,可以在“BuildingPrime”上使用触发器(“而不是”或“之后”)


希望这有帮助

听起来像是在复制数据。您真的需要这样做吗?您使用的是哪种DBMS?博士后?甲骨文?这是个糟糕的设计。关系数据库是关系数据库。如果您在一个与另一个表相关的表中进行了更改,则当您需要使用该数据时,无需进行任何更改,您可以将该数据加入到包含所需数据的表中。
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