dongtuota3633 2012-09-18 04:00
浏览 82
已采纳

重新排列主键

I have a PHP page which interacts with this small MySQL database table with a simple structure. ID, Name, Address are the fields. ID is the primary key.

+------+------------+-------------+
|  ID  |   Name     |   Country   |
|______|____________|_____________|
| E001 |  Stephen   |   America   |
| E002 |  John      |   Britain   |
| E003 |  Kate      |   Canada    |
| E004 |  Carlos    |   Spain     |
| E005 |  James     |   Australia |
|______|____________|_____________|

If I remove the record at E003, it looks like this.

+------+------------+-------------+
|  ID  |   Name     |   Country   |
|______|____________|_____________|
| E001 |  Stephen   |   America   |
| E002 |  John      |   Britain   |
| E004 |  Carlos    |   Spain     |
| E005 |  James     |   Australia |
|______|____________|_____________|

A gap appears between E002 and E004.

Is there a way to fill in that gap? Like this

+------+------------+-------------+
|  ID  |   Name     |   Country   |
|______|____________|_____________|
| E001 |  Stephen   |   America   |
| E002 |  John      |   Britain   |
| E003 |  Carlos    |   Spain     |
| E004 |  James     |   Australia |
|______|____________|_____________|

Earlier record which had E004, fall into the place of E003. Former E005 gets the number E004 and so on. Like the records take a step back.

Is there a way to do this programmatically?

  • 写回答

3条回答 默认 最新

  • doushenyi9104 2012-09-18 04:10
    关注

    Is there a reason you need to renumber them? The key values shouldn't really matter. If they do (i.e., they are used for outside purposes), consider having the external key be a regular column in the table and let the primary key be an auto-increment integer field. Even if you do this, you still probably shouldn't be renumbering keys. That would mean that all external dependencies would need to be updated as well. There's just not much value in doing it.

    But, if you have to...

    If the key is auto-increment (which it should be), you can do this:

    ALTER TABLE MyTable DROP ID;
    ALTER TABLE MyTable ADD COLUMN ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT FIRST;
    

    If it's not, then you can do several things, but the easiest might be to use variables to act as a counter. To make this easier, please don't use a string primary key, but instead use a plain numeric primary key.

    SET @id = 0;
    
    UPDATE MyTable
    SET ID = (@id := @id + 1)
    ORDER BY ID;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 为什么在iis上部署网站,服务器可以访问,但是本地电脑访问不了
  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数
  • ¥15 ADS时域 连续相位观察方法
  • ¥15 Opencv配置出错
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像
  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused