Jump to content

is it possible to use LAST_INSERT_ID () across queries


emehrkay

Recommended Posts

Example

 

INSERT INTO question (sti_id, question_type, creation_date, last_updated_date, question_text) VALUES (1, 1, NOW(), NOW(), 
');
INSERT INTO test_question (test_id, question_id, question_num) VALUES (4, LAST_INSERT_ID(), 1);
INSERT INTO question_option (question_id, question_option_id, creation_date, last_updated_date, question_option_text, question_option_correct) VALUES   
( 1, 1, NOW(), NOW(), '', 1),
( 1, 2, NOW(), NOW(), '', 0),	
( 1, 3, NOW(), NOW(), '',0),
( 1, 4, NOW(), NOW(), '', 0);

 

the question_id in my question_option insert, needs to be the last_insert_id() of the question insert. Is that at all possible using strictly mysql, no php?

this is what i did, let me know if there is a more efficient way to handle it

 

 

INSERT INTO question_option (question_id, question_option_id, creation_date, last_updated_date, question_option_text, question_option_correct) VALUES   
( (SELECT question_id FROM question ORDER BY question_id DESC LIMIT 1), 1, NOW(), NOW(), '', 1),
( (SELECT question_id FROM question ORDER BY question_id DESC LIMIT 1), 2, NOW(), NOW(), '', 0),	
( (SELECT question_id FROM question ORDER BY question_id DESC LIMIT 1), 3, NOW(), NOW(), '',0),
( (SELECT question_id FROM question ORDER BY question_id DESC LIMIT 1), 4, NOW(), NOW(), '', 0);

use SET to store the insert id between queries.

 

SET @question_id = last_insert_id();

INSERT INTO question_option (question_id, question_option_id, creation_date, last_updated_date, question_option_text, question_option_correct) VALUES   
( @question_id, 1, NOW(), NOW(), '', 1),
( @question_id, 2, NOW(), NOW(), '', 0),	
( @question_id, 3, NOW(), NOW(), '',0),
( @question_id, 4, NOW(), NOW(), '', 0);

  • 5 months later...

use SET to store the insert id between queries.

 

SET @question_id = last_insert_id();

INSERT INTO question_option (question_id, question_option_id, creation_date, last_updated_date, question_option_text, question_option_correct) VALUES   
( @question_id, 1, NOW(), NOW(), '', 1),
( @question_id, 2, NOW(), NOW(), '', 0),	
( @question_id, 3, NOW(), NOW(), '',0),
( @question_id, 4, NOW(), NOW(), '', 0);

 

thank you, i just revisited this and used it

FYI, this will also work, assuming there are no inserts in between:

 

NSERT INTO question_option (question_id, question_option_id, creation_date, last_updated_date, question_option_text, question_option_correct) VALUES   
( LAST_INSERT_ID(), 1, NOW(), NOW(), '', 1),
( LAST_INSERT_ID(), 2, NOW(), NOW(), '', 0),	
( LAST_INSERT_ID(), 3, NOW(), NOW(), '',0),
( LAST_INSERT_ID(), 4, NOW(), NOW(), '', 0);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.