简体   繁体   中英

Copy a table data from one database to another database SQL

I have had a look at similar problems, however none of the answers helped in my case.

Just a little bit of background. I have Two databases, both have the same table with the same fields and structure. Data already exists in both tables. I want to overwrite and add to the data in db1.table from db2.table the primary ID is causing a problem with the update.

When I use the query:

USE db1;
INSERT INTO db2.table(field_id,field1,field2)
SELECT table.field_id,table.field1,table.field2
FROM table;

It works to a blank table, because none of the primary keys exist. As soon as the primary key exists it fails.

Would it be easier for me to overwrite the primary keys? or find the primary key and update the fields related to the field_id? Im really not sure how to go ahead from here. The data needs to be migrated every 5min, so possibly a stored procedure is required?

在要移动数据的表上的“ 身份规范”中 ,将“ IsIdentity”设置为“ 否” ,然后在执行脚本后,再次将其设置为“ 是”

I ended up just removing the data in the new database and sending it again.

DELETE FROM db2.table WHERE db2.table.field_id != 0;
USE db1;
INSERT INTO db2.table(field_id,field1,field2)
SELECT table.field_id,table.field1,table.field2
FROM table;

Its not very efficient, but gets the job done. I couldnt figure out the syntax to correctly do an UPDATE or to change the IsIdentity field within MariaDB, so im not sure if they would work or not.

The overhead of deleting and replacing non-trivial amounts of data for an entire table will be prohibitive. That said I'd prefer to update in place (merge) over delete /replace.

USE db1;
INSERT INTO db2.table(field_id,field1,field2)
SELECT t.field_id,t.field1,t.field2
FROM table t
ON DUPLICATE KEY UPDATE field1 = t.field1, field2 = t.field2

This can be used inside a procedure and called every 5 minutes (not recommended) or you could build a trigger that fires on INSERT and UPDATE to keep the tables in sync.

first you should try to add new records then update all records.you can create a procedure like below code

PROCEDURE sync_Data(a IN NUMBER ) IS
  BEGIN

   insert into db2.table
     select *
       from db1.table t
         where t.field_id not in (select tt.field_id from db2.table tt);

     begin
       for t in (select * from   db1.table) loop
        update db2.table aa
         set aa.field1  = t.field1,
           aa.field2     = t.field2 
     where aa.field_id = t.field_id;
  end loop;
 end;

END sync_Data
INSERT INTO database1.tabledata SELECT * FROM database2.tabledata;

但是您必须使varchar长度的长度大于或等于database2并保持相同的列名

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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