Jump to content

re-number of mysql "id" field


sungpeng

Recommended Posts

  • 8 months later...

I'm sort of a neat freak myself. While I'm aware of the dangers, I just couldn't help but try to figure this one out for myself. I wanted to renumber my id field after a deletion and I just couldn't take no for an answer. I'm sure there's a cleaner way, but here's how I did it.

 

$getRows = mysql_query("SELECT ID FROM $table") or die (mysql_error());
$numGetRows = mysql_num_rows($getRows);        
   	
$getLastRow = mysql_query("SELECT ID FROM $table ORDER BY ID DESC LIMIT 1") or die (mysql_error());
$row = mysql_fetch_assoc($getLastRow);

$maxID = $row['ID'];
    
$difference = (int)$maxID - (int)$numGetRows;

$renumber = mysql_query("UPDATE $table SET ID = ID - ('$difference') WHERE ID + ('$difference') > ('$maxID') ORDER BY ID ASC") or die (mysql_error());

 

I'm sure you can use SELECT COUNT instead of SELECT ID, and remove (int) from the $numGetRows variable. I didn't say it was optimized, but it does work!

 

Hope that helps!

Link to comment
Share on other sites

Hi

 

While fully echoing what Fenway and Mchl say in this ancient thread, it can be done even easier than that with the following:-

 

SET @rownum = 0;
update idtest SET Id = (@rownum:=@rownum+1) ORDER BY id

 

It really is a horrible idea though and updating the primary key like this will destroy any relationships based on it.

 

All the best

 

Keith

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.