doucou19961205 2014-10-08 19:36
浏览 23

SQL ID值自动向上移动

I have a table which an auto-increment ID column. I want my database to automatically change the ID value so there is always an ID value of 1.

For example:

ID Firstname Lastname

1  John      Smith
2  Charlie   Jacobs
3  Jason     young

I want it so that if I delete row ID 1 then row ID 2 changes to ID 1 and row ID 3 changes to ID 2. Like this:

ID Firstname Lastname

1  Charlie   Jacobs
2  Jason     young

I want to be able to then add names after which would carry on from ID 3. Preferably I was wondering if there was a setting in SQL that can do this automatically. If this isn't possible then a PHP script would be the second best thing.

  • 写回答

1条回答 默认 最新

  • douzhang3898 2014-10-09 04:50
    关注

    That is not a right thing to do. Why do you want to do that? This would mess up your primary key values. So don't do it. Coming to the solution

    If you are displaying this inside a form, just generate a row number for each row in your select statement. It will not have any gaps in between. MYSQL Generating Row Numbers

    SELECT @row_number:=@row_number+1 AS row_number,db_names FROM mysql_testing, 
    (SELECT @row_number:=0) AS t
    ORDER BY db_names;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题