Jump to content

Single query to INSERT with next auto increment


UnfoX

Recommended Posts

Hi all,

 

Lets have a table which has to columns. first column (id) has auto increment property. What I want is, when I insert a new row, I want to duplicate the next auto increment value (next id) to the second column (dID). I want to make it with one query.

 

Table example:

id  -  dID

1    |  1

2    |  2

 

PS: I don't want to use a method like max(id) + 1.. because the next increment value may not be +1 if a row is deleted in between.

 

Any suggestions?

Thanks

Link to comment
Share on other sites

LAST_INSERT_ID().... and php mysqli library has a function for this too.

 

Thanks but it's not what I'm looking for. I need next insert id, not the last one :) If you say that next will be last_insert_id() + 1, I think it will not be correct in all cases.

Link to comment
Share on other sites

Hi,

Try this, you will get next auto increment id as "Auto_increment".

$query= "SHOW TABLE STATUS LIKE TblName";

 

thanks

 

 

 

 

There's a reason it's suggested to never depend on data that's not yet there....

 

 

What if a separate connection to the database makes a query between the time that this query is run and the subsequent insert being ran?  Then you have a collision :).

Link to comment
Share on other sites

I want to make it with one query.

You cannot. The actual auto-increment value that is inserted is not available inside the actual query. It is only available after the INSERT query has executed.

 

One could try to use the mysql LAST_INSERT_ID() in your single INSERT query to assign the value to a second field, but you will find that it behaves according to the documentation and it does not return the value that was just inserted until the INSERT query has executed.

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.