MySQL自动增量是如何工作的?
我刚刚使用 MySQL 查询浏览器创建一个新表,并注意到自动增量列下有一个勾号。这是如何运作的?
以编程方式添加到数据库时,我是否只添加一个数字,然后数据库自动递增该数字?
每次新用户在我的网站上注册时,我希望他们的客户 ID(仅限整数)自动递增,因此我不必尝试随机生成唯一的编号。
这可以简单地完成吗?
谢谢你!
I was just creating a new table using MySQL Query Browser, and noticed there's a tick under Auto Increment Column. How does that work?
When adding to the database programatically, do I just add a number, and then the database automatically increments that number?
Everytime a NEW user registers on my site, I want their Customer ID (integer only) to auto increment, so I don't have to try and randomly generate a unique number.
Can this be done simply?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,这就是
AUTO_INCRMENT
的确切目的。它查看该表的当前增量值,并自动为新进入的行存储该值加 1。您可以从INSERT
语句中省略该字段,MySQL 将为您处理每个新出现的行,并为每行提供其自己的唯一 ID。Yes, that's the exact purpose of
AUTO_INCREMENT
. It looks at whatever is the current increment value for that table, and stores that value plus 1 for the new row that comes in, automatically. You can omit that field from yourINSERT
statements and MySQL will handle it for you for every new row that comes in, giving each row its own unique ID.当您启用自动增量时,每当创建新记录时,都会自动添加 ID。示例:
如果表中有 1 条 ID 为 1 的记录,并且您添加了一条新记录,则 ID 将自动为 2。
When you enable Auto Increment an ID will always get automatically added whenever a new record is made.. Example:
If you have 1 record with ID 1 in your table and you add a new record, the ID will automatically be 2.
是的,这就是
auto_increment
的工作方式。每个新行的值都会递增
值是唯一的,不可能重复
如果删除一行,该行的
auto_increment
列将不会被重新分配。可以使用 mySQL 函数
LAST_INSERT_ID()
访问最后插入行的auto_increment
值,但它必须在插入查询,在同一数据库连接中mySQL 参考
Yes, that's the way
auto_increment
works.The value will be incremented for each new row
The value is unique, duplicates are not possible
If a row is deleted, the
auto_increment
column of that row will not be re-assigned.The
auto_increment
value of the last inserted row can be accessed using the mySQL functionLAST_INSERT_ID()
but it must be called right after the insert query, in the same database connectionmySQL Reference
还有 1 个,
您也可以插入您自己的值(即您的随机值)。
1 more,
You can insert your own value also (ie your random value).
是的。 Auto_Increment 列的工作方式就像他们所说的那样。提示
INSERT 时,使用 NULL 或省略列
使用 LAST_INSERT_ID() (或 API 等效项)获取最后生成的值。
出于安全和业务逻辑原因,通常最好不要直接使用客户标识符的键值。考虑使用散列/随机代理客户密钥。
塔
Yes. Auto_Increment columns work like they say on the tin. Tips
when INSERT - ing, use NULL or omit the column
Use LAST_INSERT_ID() (or API equivalents) to obtain the last generated value.
for security and business logic reasons, it's usually better form to not directly use a key value for a customer identifier. Consider using Hashed / randomised surrogate customer keys instead.
Ta