How does MySQL Auto Increment work?

后端 未结 5 893
星月不相逢
星月不相逢 2020-12-01 21:15

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 p

相关标签:
5条回答
  • 2020-12-01 21:55

    1 more, You can insert your own value also (ie your random value).

    0 讨论(0)
  • 2020-12-01 22:05

    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 your INSERT statements and MySQL will handle it for you for every new row that comes in, giving each row its own unique ID.

    0 讨论(0)
  • 2020-12-01 22:09

    When adding to the database programatically, do I just add a number, and then the database automatically increments that number?

    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 function LAST_INSERT_ID() but it must be called right after the insert query, in the same database connection

    mySQL Reference

    0 讨论(0)
  • 2020-12-01 22:11

    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.

    0 讨论(0)
  • 2020-12-01 22:16

    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

    0 讨论(0)
提交回复
热议问题