如何使用 PHP 为 MySQL 表中的每一行重新分配 AUTO_INCREMENT 列
我有一个图片库,网站成员可以将图片上传到其中。当上传图片时,会写入 MySQL 行,其中包含有关图片、成员等的各种信息。该行使用 AUTO_INCRMENT 创建其 ID,以便 getimage.php?id=XX
可以获取要显示的图像。
我使用 for 循环遍历 ID 以显示图库中的图像。
例如,如果我删除第 5 行/图像,则 AUTO_INCRMENT 将从 123456789
变为 12346789
。
我想从头开始为 MySQL 表中的每一行重新分配 ID。所以 12346789 变成 12345678。我将如何实现这一目标?
I have an image gallery which website members can upload images to. When an image is uploaded, a MySQL row is written, containing various pieces of information about the image, member, etc. This row uses AUTO_INCREMENT to create its ID, so that getimage.php?id=XX
can fetch the image to be displayed.
I loop through the IDs with a for-loop to display the images within the gallery.
If I delete the 5th row/image, for example, the AUTO_INCREMENT goes from 123456789
to 12346789
.
I would like to re-assign the ID to each row in the MySQL table, starting from the ground up. So 12346789 becomes 12345678. How would I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我发现这工作得很好而且很快,所以这里是:
我知道这不是正确的方法,但是对于我的具体情况来说,这正是所需要的。我使用的表中没有任何内容被另一个表引用或引用到另一个表。
I found this to work perfectly and quite quickly so here it is:
I know this isn't the proper approach however for my specific situation this is exactly what was needed. There is nothing within the table I was using that is referred to either from or to another table.
如果你希望自动递增的id始终是连续的,那就放手吧,这是一场无用的挣扎。
如果您只想重新编号一次,那很简单:
创建一个具有相同布局的新表:
将所有行复制到新表,记住不要选择auto_incrementing id,否则旧编号将被保留。
您现在已经有了连续编号。
If you want the auto-incrementing id's to always be consecutive, let it go, it's a useless struggle.
If you just want to renumber once, that's easy:
Create a new table with the same layout:
Copy all rows to the new table, remember to not select the auto_incrementing id, otherwise the old numbering will be retained.
You now have consecutive numbering.
使用用户定义变量:
使用示例
Using user-defined variables:
Example use
正如其他人已经指出的,这是错误的方法,但如果您需要重新编号(例如,它对于排序列有效),这里是查询:
并且由于您使用的是自动增量,因此必须重置它
但是请注意,我发布此内容仅用于教育目的。这是错误的做法!当您单击下一个/上一个时,不要在查询中提供确切的 ID,而是
选择相册中的所有记录并循环它们,甚至更好。
As other already stated, this is the wrong approach, but in case you need renumbering (it's valid for sort column for example), here is the query:
And since you are using auto-increment, you have to reset it
But please, note, I post this for education purposes only. This is the wrong approach! Instead of providing the exact ID in the query when you click next/prev, do
Or even better, select all records in the album, and loop them.