简体   繁体   English

MySQL 更新两个与第一个不同的表

[英]MySQL UPDATE Two Tables with Differences From The First

I have two tables table1 and master.我有两个表 table1 和 master。 Master is the master database of contacts. Master 是联系人的主数据库。 Table1 contains recent contact information from a survey of respondents in a study.表 1 包含来自一项研究中受访者调查的最新联系信息。

table1 contains current information - both tables are connected by the common variable ID table1 包含当前信息 - 两个表都通过公共变量 ID 连接

here is the select query (it works perfectly) - it finds all the records where EITHER field1 or field2 are different between table1 and the master table这里是 select 查询(它完美地工作) - 它找到所有记录,其中 field1 或 field2 在 table1 和主表之间不同

SELECT
t1.ID,
t1.field1,
m.field1,
t1.field2,
m.field2
FROM
table1 t1
INNER JOIN master m ON t1.ID = m.ID
where 
(
   (t1.field1 <> m.field1) OR
(t1.field2 <> m.field2)

)

My question is this: how can I transform the SELECT statement into an UPDATE statement so that all the records with different values in table1 overwrite the values in the master table?我的问题是:如何将 SELECT 语句转换为 UPDATE 语句,以便 table1 中具有不同值的所有记录覆盖 master 表中的值?

Thank you.谢谢你。

You can use the following update.您可以使用以下更新。
The where clause does not change the final result because we will overwrite rows which are already correct with the same value. where 子句不会更改最终结果,因为我们将用相同的值覆盖已经正确的行。

UPDATE t1
INNER JOIN master ON t1.id = master.id
SET 
  t1.field1 = m.field1,
  t1.field2 = m.field2
WHERE t1.field1 <> m.field1
OR t1.field2 <> m.field2;

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM