使用 JOIN 匹配两个或多个值的 SQL UPDATE

SQL UPDATE using JOIN that matches two or more values(使用 JOIN 匹配两个或多个值的 SQL UPDATE)
本文介绍了使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)