Welcome to the dBforums forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions, articles and access our other FREE features. By joining our free community you will have access to post topics, communicate privately with other members (PM), respond to polls, upload your own photos and access many other special features. Registration is fast, simple and absolutely free so please, join our community today!

If you have any problems with the registration process or your account login, please contact contact support.

If you prefer not to see double-underlined words and corresponding ads, place your cursor
here for ContentLink opt out.

Go Back  dBforums > Database Server Software > MySQL > Nested Inserts?

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 10-16-07, 15:24
sammydafish sammydafish is offline
Registered User
 
Join Date: Feb 2004
Posts: 21
Nested Inserts?

I have table configuration where I need to create a parent record in one table and then create multiple child records in other tables linked by a foreign key.

when the 1st set of records is created, there is only one child record in each child table, so I'd like to be able to do something like this

INSERT INTO header SET foo=5, default_child=(INSERT INTO child_table SET bar=9)

and have the auto increment value for the child_table be returned and inserted into the default_child field. Is there any way to do this?
Reply With Quote
  #2 (permalink)  
Old 10-16-07, 22:50
thrash.zhai thrash.zhai is offline
Registered User
 
Join Date: Oct 2007
Posts: 3
If your version 0f mysql is late 5.0,
it is possible with trigger
Reply With Quote
  #3 (permalink)  
Old 10-17-07, 06:25
aschk aschk is offline
Registered User
 
Join Date: Mar 2007
Location: 636f6d7075746572
Posts: 734
Do it in a transaction:

1) Begin transaction
2) Insert parent record first
3) Use last_insert_id() to get ID of parent record and SET @parent
4) Insert child record using parent key
5) Use last_insert_id() to update parent record with default child.
6) Insert child record using parent key
7) Insert child record using parent key
8) Insert child record using parent key
...
...
...
last) Close transaction

If any of the above fails the transaction will rollback.
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On