根据在另一列中具有相同值的其他三列更新一列 table

Update one column based on three other column which have same value in another table

我有两个表,表 1 中有 3 个具有相同值的字段和一个关系字段。让我解释一下。

table1
------
id
column1
column2
column3
table2_id
table2
-------
id
column1
column2
column3

在表2中; column1、column2 和 column3 对于不同的 id 可以具有相同的值。例如:

table2
-------
1, 2, 3, 4
2, 2, 3, 4
3, 4, 5, 6

你看,前两条记录只有id不同。其他都一样。同样在表 1 中:

table1
-------
1, 2, 3, 4, null
2, 4, 5, 6, null

我想更新表 1 的 table2_id 字段(在示例中为空),仅针对表 1 中具有第 1 列、第 2 列、第 3 列的特定记录的记录。

所以我预计:

table1
------
1, 2, 3, 4, null
2, 4, 5, 6, 3

第一条记录仍然为空,因为那里可以链接 2 个不同的 ID。但是对于第二条记录,table2_id只能是'3'

如何编写此更新过程的查询?

您可以使用额外的 table 或 CTE 来解决它,以识别重复或真实的记录。 GROUP BY 或连接可用于检查重复项。

请注意,如果列可以为空,您还需要检查方程中的空值。

with GenuineData as (
   select
      min(t2.Id) id
   from
      Table2 t2
   group by
      t2.Column1,
      t2.Column2,
      t2.Column3
   having
      count(*) = 1
)
update t1 set
   t1.Table2Id = t2.Id
from
   Table1 t1
   join Table2 t2 on t2.Column1 = t1.Column1 and t2.Column2 = t1.Column2 and t2.Column3 = t1.Column3
   join GenuineData gd on gd.id = t2.Id

如果列可以为空,您可以在等式中使用 ISNULL(),或者为了获得更好的性能,连接 Table2 的扩展标准如下:

   join Table2 t2 on
      (t2.Column1 = t1.Column1 or (t1.Column1 is null and t2.Column1 is null))
      and (t2.Column2 = t1.Column2 or (t1.Column2 is null and t2.Column2 is null))
      and (t2.Column3 = t1.Column3 or (t1.Column3 is null and t2.Column3 is null))