mysql 递减_MySQL - 自动递减值

bd96500e110b49cbb3cd949968f18be7.png

Let's say that I've got a table, like that (id is auto-increment):

id | col1 | col2

1 | 'msg'| 'msg'

2 | 'lol'| 'lol2'

3 | 'xxx'| 'x'

Now, I want to delete row number 2 and I get something like this

id | col1 | col2

1 | 'msg'| 'msg'

3 | 'xxx'| 'x'

The thing is, what I want to get is that:

id | col1 | col2

1 | 'msg'| 'msg'

2 | 'xxx'| 'x'

How can I do that in the EASIEST way (my knowledge about MySQL is very poor)?

解决方案

You shouldn't do that.

Do not take an auto-incremented unique identifier as an ordinal number.

The word "unique" means that the identifier should be stuck to its row forever.

There is no connection between these numbers and enumerating.

Imagine you want to select records in alphabetical order. Where would your precious numbers go?

A database is not like an ordered list, as you probably think. It is not a flat file with rows stored in a predefined order. It has totally different ideology. Rows in the database do not have any order. And will be ordered only at select time, if it was explicitly set by ORDER BY clause.

Also, a database is supposed to do a search for you. So you can tell that with filtered rows or different ordering this auto-increment number will have absolutely nothing to do with the real rows positions.

If you want to enumerate the output - it's a presentation layer's job. Just add a counter on the PHP side.

And again: these numbers supposed to identify a certain record. If you change this number, you'd never find your record again.

Take this very site for example. Stack Overflow identifies its questions with such a number:

stackoverflow.com/questions/3132439/mysql-auto-decrementing-value

So, imagine you saved this page address to a bookmark. Now Jeff comes along and renumbers the whole database. You press your bookmark and land on the different question. Whole site would become a terrible mess.

Remember: Renumbering unique identifiers is evil!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值