SQL UPDATE using JOIN that matches two or more values(使用 JOIN 匹配两个或多个值的 SQL UPDATE)
问题描述
我正在使用 JOIN 执行 SQL UPDATE,但该 JOIN 可以匹配多个值.假设我们有以下表格:
I'm performing an SQL UPDATE with JOIN, but that JOIN can match more than one value. Let's say we have the following tables:
Table_1 Table_2
col_a | col_b col_a | col_b
--------------- ---------------
1 | A 1 | X
2 | B 1 | Y
3 | C 3 | Z
然后我执行以下查询:
UPDATE
t1
SET
t1.col_b = t2.col_b
FROM
Table_1 t1
JOIN
Table_2 t2 ON t1.col_a = t2.col_a;
结果如下:
Table_1 Table_2
col_a | col_b col_a | col_b
--------------- ---------------
1 | X 1 | X
2 | B 1 | Y
3 | Z 3 | Z
我需要做的是用匹配的最后一个值更新 Table_1;所以在这种情况下,我需要这个结果:
What I need to do is to update the Table_1 with the last value matched; so in this case, I would need this result:
Table_1 Table_2
col_a | col_b col_a | col_b
--------------- ---------------
1 | Y 1 | X
2 | B 1 | Y
3 | Z 3 | Z
推荐答案
如果你有办法定义 Table_2 中记录的顺序(最后是什么意思?)你可以使用窗口函数来过滤 Table_2 只包含最后一个每组匹配记录的记录:
Provided you have a way to define the order of records in Table_2 (what does last mean?) you can use window functions to filter Table_2 to only include the last record of each group of records that match:
UPDATE
t1
SET
t1.col_b = t2.col_b
FROM
Table_1 t1
JOIN
(SELECT col_a, col_b,
ROW_NUMBER() OVER (PARTITION BY col_a
ORDER BY <order by field list goes here> DESC) AS RNo
FROM Table_2) t2 ON t1.col_a = t2.col_a AND t2.RNo=1;
在 order by 字段为 col_b 的特殊情况下,您可以简单地使用(这适用于所有版本的 SQL Server):
In the special case that the order by field is col_b then you can simply use (this works on all versions of SQL Server):
UPDATE
t1
SET
t1.col_b = t2.col_b
FROM
Table_1 t1
JOIN
(SELECT col_a, MAX(col_b) AS col_b
FROM Table_2
GROUP BY col_a) t2 ON t1.col_a = t2.col_a;
这篇关于使用 JOIN 匹配两个或多个值的 SQL UPDATE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JOIN 匹配两个或多个值的 SQL UPDATE
基础教程推荐
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 无法解决整理冲突 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
