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!

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

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.