Inserting data into separate tables quickly and reliably
Let's say we get the following data from a CSV file:
account_number balance customer name
100 500.00 GERN BLANSTON
101 800.00 GERN BLANSTON
102 200.00 OPRAH WINFREY
This represents two accounts belonging to Gern Bla开发者_开发技巧nston and one belonging to Oprah Winfrey. Now let's say we have a customer
table and an account
table. We could hypothetically insert the data using just two INSERT
statements:
INSERT INTO customer
(name)
VALUES
('GERN BLANSTON'),
('OPRAH WINFREY')
and
INSERT INTO account
(account_number, balance, customer_id)
VALUES
(100, 500.00, ???),
(101, 800.00, ???),
(102, 200.00, ???)
If we knew the IDs for Gern Blanston and Oprah Winfrey, we could of course use those IDs in the second INSERT
statement and it would work fine. But one way or another, we need to get those IDs.
My question: is there a fast way to find out, or at least keep track of, the IDs of each inserted customer? Inserting each row individually and then getting LAST_INSERT_ID()
is too slow for me (I have up to 65,000 accounts in each CSV file). Looking up the customer ID each time I insert a new account is also too slow.
Or, if you want to sidestep that particular question and recommend a different solution, I'm open to that as well. I'm using MySQL.
add another column for table account
, which store customer_name
, after complete the insertion, just update account set customer_id=(select customer.customer_id from customer where customer.customer_name=account.customer_name;
hope this alternative workaround simplify the complexity
also, change your customer table
to have auto_increment for customer_id
精彩评论