If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Last Insert Question

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 02-24-04, 01:27
Jen76 Jen76 is offline
Registered User
 
Join Date: Jan 2004
Location: California
Posts: 10
Last Insert Question

I know that with Last_Insert_ID I can get the last inserted ID...but if the insert inserted more than one row, it only pulls the first id inserted within that group. How can I get all of the ID's inserted in that group?
Reply With Quote
  #2 (permalink)  
Old 02-24-04, 14:31
aus aus is offline
Registered User
 
Join Date: Oct 2003
Location: Denver, Colorado
Posts: 137
Re: Last Insert Question

Do you always know how many rows you insert?
Reply With Quote
  #3 (permalink)  
Old 02-24-04, 14:51
Mastulator Mastulator is offline
Registered User
 
Join Date: Feb 2004
Posts: 14
Well, assuming you can guarantee that nobody will write to the table at the same time that you are, you could always count the number of elements you're inserting, fetch the ID of the first one that was inserted, and then simply correlate them.

No idea on whether MySQL has transactions or any sort of normal locking though (I'm a PGSQL guy).
__________________
The Mastulator
Reply With Quote
  #4 (permalink)  
Old 02-24-04, 15:08
aus aus is offline
Registered User
 
Join Date: Oct 2003
Location: Denver, Colorado
Posts: 137
Re: Last Insert Question

Actually, you could do things this way:
Code:
LOCK TABLES inserttable WRITE;
INSERT INTO inserttable... <your insert statement>;
SELECT autoid FROM inserttable
WHERE autoid >= LAST_INSERT_ID();
UNLOCK TABLES;
That will give you all the ids that were inserted. I know that MyISAM tables do not use ids missing from the middle of the table, so you are safe there. The LOCK TABLES statement will guarantee that nobody interferes with your insert.
Reply With Quote
  #5 (permalink)  
Old 02-27-04, 09:52
Jen76 Jen76 is offline
Registered User
 
Join Date: Jan 2004
Location: California
Posts: 10
Thanks aus!! Works perfect!
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

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