SQL Update statement with ID from other table, using relations

问题描述 投票:0回答:1

我现在需要这个:

update [dbo].[ProductionCostCenter] 
set signerId = 999 
where ProductionCostCenter.id = ReasonCode.ProductionCostCenterId 
  and ReasonCode.Id = 77777

我这样做的另一种方法是从第一个表中获取 ID,然后在第二个语句中使用它来更新我的相关值。

我正在使用 SQL Server。

写到这里我想到了

update [dbo].[ProductionCostCenter] 
set signerId = 999 
where id in (select ProductionCostCenterId 
             from ReasonCode 
             where Id = 77777)

这是更好的方法吗?

sql sql-server sql-update subquery inner-join
1个回答
1
投票

使用

in
和子查询的第二个查询应该可以工作。我仍然会在这里推荐
exists

update ProductionCostCenter p
set signerId = 999
where exists (
    select 1 from ReasonCode r where r.id = 77777 and r.ProductionCostCenterId  = p.id
)

exists
usually
in
表现更好,尤其是在正确的索引到位的情况下:

create index idxProductionCostCenter on ReasonCode(id, ProductionCostCenterId);

这假设两个表之间存在 1-N 关系。如果你有一对一的关系(这似乎不太可能),

join
会感觉更自然,正如 Thom A 评论的那样:

update p
set signerId = 999
from ProductionCostCenter p
inner join ReasonCode r on r.ProductionCostCenterId  = p.id
where r.id = 77777
© www.soinside.com 2019 - 2024. All rights reserved.