【问题标题】:SQL Self Join UpdateSQL 自联接更新
【发布时间】:2021-09-29 09:36:35
【问题描述】:

我需要通过自连接来以程序方式更新表。使用 SQL Server 2019。

CREATE TABLE Sect
(
     Section_Id INT, 
     Locale VARCHAR(10), 
     Record_Id INT, 
     Section_Id_1 INT
);
   
INSERT INTO Sect (Section_Id, Locale, Record_Id, Section_Id_1)
VALUES
(100, 'US', 1, Null),
(101, 'CA', Null, 100),
(101, 'MD', Null, 100)

目标是使用匹配的Record_ID 更新Record_Id 的空值,其中Section_Id_1 等于Section_ID

这是预期的结果:

100|US|1|Null
101|CA|1|100
101|MD|1|100

我认为我很接近:

UPDATE t1 
SET Record_Id = t2.Record_Id
FROM Sect t1
INNER JOIN Sect t2 ON t1.Section_Id_1 = t2.Section_Id
WHERE t1.Record_Id IS NULL

感谢您的帮助。

【问题讨论】:

  • 你的问题是什么?
  • 如何获得“预期结果”?
  • 然后在 Fiddle 上向我们展示
  • 您的查询看起来正确。
  • 我们需要minimal reproducible example,因为您的问题中没有提到crossRecord_Id - 人们可能会猜测您正在创建一个存储过程,并且当它已经存在时您已经尝试第二次创建它。但是,如果没有确切地看到您正在尝试做什么,这一切都是猜测。这就是您所说的“程序更新”吗?因为通常程序化与基于集合的相反,后者与关系数据库相反。

标签: sql sql-server tsql inner-join self-join


【解决方案1】:

我对 SQL Server 2019 不熟悉。但我认为你不需要使用 INNER JOIN,试试这个。

update
  Sect t1
set
  Record_Id = (select t2.Record_Id 
               from Sect t2 
               where t2.Section_ID = t1.Section_Id_1 
                 and t2.Record_Id is not null 
               limit 1)
where Record_Id is null
  and Section_Id_1 is not null 

【讨论】:

  • 感谢您的宝贵反馈。我只是需要睡觉。最终程序概述如下。 ...更新 t1 SET Record_Id = t2.Record_Id FROM Test_Section t1 INNER JOIN Test_Section t2 ON t1.Section_Id_1 = t2.Section_Id WHERE t1.Record_Id 为 NULL ...祝您愉快!
猜你喜欢
  • 1970-01-01
  • 2012-10-04
  • 2014-06-09
  • 2013-03-31
  • 2016-09-23
  • 2022-01-16
  • 2021-10-06
  • 2011-03-28
  • 1970-01-01
相关资源
最近更新 更多