dexterdeng
dexterdeng

Reputation: 249

How to insert many related records in one sql file

I want to insert many records in 3 tables, businesses, business_categories (business_id), business_details(business_id), I want to insert many data.

as you can see, the data in business_categories and business_details will need to use the business's id, and when inserting data, I still don't know the business id.

in the past, I was writing a ruby script to do that things, but it's pretty slow. and now I want to write a script to generate sql file directly, it can be the fast way.

I would write this.

insert into businesses(name, ..) values ("blabla", ...)
insert into business_categories(business_id, ..) values(? ..)
insert into business_details(business_id, ..) values(? ..)

Is it possible to set the right value to the ? ?

thanks.

Upvotes: 0

Views: 88

Answers (1)

edhedges
edhedges

Reputation: 2718

You could save the last inserted id to a variable and set that value in the following inserts.

https://stackoverflow.com/a/17112962/1165441

This answer has some info that is really good.

Upvotes: 1

Related Questions