Jump to content

Using last insert id in query


Kieran Menor

Recommended Posts

Here is my table:

 

TABLE `categories` (

  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  `name` varchar(255) NOT NULL,

  `order` int(10) unsigned NOT NULL,

  PRIMARY KEY (`id`)

)

 

Now, consider this query:

 

INSERT INTO `categories` (`name`, `order`) VALUES ('Test', ????)

 

I want the "order" field to have the same value as the ID field will get when the row is inserted. Is this possible?

 

Edit: And if so, how. :P

Link to comment
Share on other sites

Well, I would rather do it at insert time, but if that's not possible I suppose I can just update the row afterwards.

 

I see.  Sorry, I'm not aware of a way to do this in a single query.

Link to comment
Share on other sites

This is my understanding:

 

LAST_INSERT_ID() & mysql_insert_id()

 

This 2 guys work on a connection basis.

 

If a host connects to MySQL and inserts a record, you can get the query ID using LAST_INSERT_ID() & mysql_insert_id() after executing the query.

 

If another hosts connects an execute LAST_INSERT_ID() & mysql_insert_id() will get 0, this is because no record has been inserted with this connection.

 

The only solution I can thing of to do what the OP wants, is to run a separate query or perhaps create a transaction.

 

Using two queries:

INSERT INTO `categories` (`name`) VALUES ('Test');

UPDATE `categories` SET `order`=LAST_INSERT_ID() WHERE Id=LAST_INSERT_ID();

 

Angel

 

 

 

Link to comment
Share on other sites

The only solution I can thing of to do what the OP wants, is to run a separate query or perhaps create a transaction.

 

That's no what the OP wants.  Please read the previous posts.

Link to comment
Share on other sites

The OP wants to do this:

 

INSERT INTO `categories` (`name`) VALUES ('Test');

UPDATE `categories` SET `order`=LAST_INSERT_ID() WHERE Id=LAST_INSERT_ID();

 

with a single query.

 

The only solution I can think of to achieve the final result that OP will get, is to run a separate query or perhaps create a transaction.  :'(

 

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.