简体   繁体   English

MYSQL Maria DB-比较2个表A和B并更新记录

[英]MYSQL Maria DB - Compare 2 tables A and B and update records

I have 2 tables A and B. I wanted to compare table A with table B and for any mismatched record I wanted to update the entire record from table A to Table B. We have 2 primary keys and have around 40 million records. 我有2个表A和B。我想将表A与表B进行比较,对于任何不匹配的记录,我想将整个记录从表A更新为表B。我们有2个主键,大约有4000万条记录。

Can we achieve this in one SQL or Script? 我们可以用一个SQL或脚本来实现吗? Or can I create temporary table(Table c) where I can write table A records which are mismatching and then update Table B with temporary Table C. This I would be doing in MY SQL workbench and using mariaDB DB. 或者,我可以创建临时表(表c),在其中写入不匹配的表A记录,然后使用临时表C更新表B。这将在MY SQL工作台中使用mariaDB DB进行。

Added additional information - I have 2 primary keys and 15 columns. 添加了更多信息-我有2个主键和15列。 So, Ideally have to match 13 columns and find mismatches assuming the primary key matches in both tables. 因此,理想情况下必须匹配13列并假定两个表中的主键都匹配,才能找到不匹配项。

Please assist and appreciate for any feedback. 请协助并感谢您的任何反馈。

One approach is to do an update left join of the B table to the A table, and update all columns in the former table with values from the latter. 一种方法是将B表更新为A表的左连接,并使用后者的值更新前一个表中的所有列。 Note that the WHERE clause checks to make sure that a record in B did not match to any record in A. 请注意, WHERE子句检查以确保B中的记录与A中的任何记录都不匹配。

UPDATE TABLE_B b
LEFT JOIN TABLE_A a
    ON a.col1 = b.col1 AND
       a.col2 = b.col2     -- AND all other columns
SET b.col1 = a.col1,
    b.col2 = a.col2        -- AND set all other columns
WHERE a.col1 IS NULL

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

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