douzhu1188 2017-07-28 07:44
浏览 137
已采纳

如何自动将新的id值设置为已删除行的id

I have a table with 50 rows, id column as primary key, autoincrement.

At the beginning id values where from 1 - 50;

After deleting a row, for example id=1, and inserting a new row, this will have id=51.

How can I set the new row to take first empty place, it this case id=1 automatically, instead of 51;

Also if id=5 is deleted, the next inserted row should have id=5 an so on.

  • 写回答

2条回答 默认 最新

  • dongtan7418 2017-07-28 07:58
    关注

    You can use MySQL's query variables to track the previous id and calculate the difference in the query, e,g.:

    SELECT id, id - @previous AS difference, @previous := id
    FROM test, (SELECT @previous := 0) a
    ORDER BY id;
    

    This would give you all the ids with difference. You can then wrap this into another query and SELECT the rows with difference > 1 to get the available id, e.g.:

    SELECT (id - difference + 1) AS available_id
    FROM (
     SELECT id, id - @previous AS difference, @previous := id
     FROM test, (SELECT @previous := 0) a
     ORDER BY id) b
    WHERE b.difference > 1
    LIMIT 1;
    

    Here's the SQL Fiddle.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)