简体   繁体   中英

How to insert one table to another from another database with relationships in MySQL?

In my old database, I have 2 tables:

invoices

id
dr_no
customer_name
created_at

invoice_items

id
dr_no
item_name
created_at

That is a one to many relationship. An invoice can have many invoice_item . The problem here is that instead of the id of the invoice as the reference, the dr_no is used.

I'm doing a revamp of the system and want to transfer the old database to a new one and use the invoice_id as the reference instead of the `dr_no.

The current invoices table already holds 100k records and instead of looping it an inserting it in the a new database, I used this code:

INSERT INTO new_db.invoices SELECT * FROM old_db.invoices;

This does the job but to also insert the invoice_items , I have to loop all invoices , check all invoice_items with specific dr_no and insert into new invoice_items table.

Is there a more performant way of doing this?

You could insert into the new invoice_items table using the following query:

INSERT INTO mew_db.invoice_items
SELECT
    t.id, 
    v.id,         -- invoice_id
    t.item_name,
    t.created_at
FROM old_db.invoice_items t
INNER JOIN old_db.invoices v ON v.dr_no = t.dr_no

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