简体   繁体   English

如何用表B中的数据更新表A?

[英]How to update table A with data from table B?

I am trying to update table A with two data values from table B. I thought I could do something like: 我正在尝试使用表B中的两个数据值更新表A。我认为我可以执行以下操作:

UPDATE A
SET A.DATA1= B.DATA1, A.DATA2= B.DATA2
FROM TABLE1 A, TABLE2 B
WHERE A.ID = B.ID;

What is the correct syntax? 正确的语法是什么?

The classic (non-obvious) standard SQL answer is: 经典(非显而易见)标准SQL答案是:

UPDATE A
   SET (Data1, Data2) = ((SELECT B.Data1, B.Data2
                            FROM B
                           WHERE B.ID = A.ID))
 WHERE A.ID IN (SELECT B.ID FROM B);

The correlated sub-query generates one result row (presumably) from B for each matching row in A. The WHERE clause on the UPDATE prevents you from nullifying data A where there isn't a matching row in B. The double parentheses aren't a casual typo. 相关子查询为A中的每个匹配行从B生成一个(大概是)B的结果行。UPDATE上的WHERE子句可防止您无效B中没有匹配行的数据A。双括号不是一个偶然的错字。

This is messy to write, so most DBMS provide a non-standard mechanism to do updates with a join, but the syntax used varies by DBMS. 编写起来很麻烦,因此大多数DBMS提供了一种非标准的机制来通过联接进行更新,但是所使用的语法因DBMS而异。

For SQL Server I would do: 对于SQL Server,我可以这样做:

UPDATE A SET
    A.DATA1= B.DATA1,
    A.DATA2= B.DATA2
FROM TABLE1 A
JOIN TABLE2 B on WHERE A.ID = B.ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从表B上的循环数据更新表A - Update Table A from loop data on table B MySQL如何从另一个表更新表数据? 表A中的1行映射到表B中的2行 - MySQL how to update table data from another table? 1 row in table A maps to 2 rows in table B 当 A 和 C 通过表 B 链接时,如何使用表 C 中的数据更新表 A - How can I update table A with data from table C when A and C are linked via table B 当表 C 中只有共享数据时,如何从表 B 更新表 A? - How to UPDATE Table A from Table B when only shared data is in Table C? SSIS:如何将数据从表A传输到表B,然后为每行更新表A标志列 - SSIS: How to transfer data from table A to table B and then update table A flag column for each row 从A表插入数据到B表,然后用B表ID更新A表 - Insert data from Table A to Table B, then Update Table A with Table B ID 如何从属于数据库“ A”的表更新/插入数据到属于数据库“ B”的表? - How to update / insert data from table belong to database “A” to table belong to a database “B”? 如何从表 B 值更新表 A 值? - How to update table A values from table B values? 如何使用来自表 B 列 3 Teradata 的输入更新表 A 列 3 - How to Update Table A column 3 with input from Table B column 3 Teradata 如何根据表B的数据从表A中获取数据 - How to get data from table A based on table B data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM