Can you use auto-increment in MySql with out it being the primary Key

后端 未结 6 1709
春和景丽
春和景丽 2021-01-03 08:52

I am using GUIDs as my primary key for all my other tables, but I have a requirement that needs to have an incrementing number. I tried to create a field in the table with

相关标签:
6条回答
  • 2021-01-03 09:09

    GUID's are not intended to be orderable, that's why AUTO_INCREMENT for them does not make sense.

    You may, though, use an AUTO_INCREMENT for a second column of a composite primary key in MyISAM tables. You can create a composite key over (GUID, INT) column and make the second column to be AUTO_INCREMENT.

    To generate a new GUID, just call UUID() in an INSERT statement or in a trigger.

    0 讨论(0)
  • 2021-01-03 09:12

    No, only the primary key can have auto_increment as its value.

    0 讨论(0)
  • 2021-01-03 09:24

    I would lean the other way.

    Why? Because creating a composite key gives the impression to the next guy who comes along that it's OK to have the same GUID in the table twice but with different sequence numbers.

    0 讨论(0)
  • 2021-01-03 09:27

    A GUID value is intended to be unique across tables and even databases so, make the auto_increment column primary index and make a UNIQUE index for the GUID

    0 讨论(0)
  • 2021-01-03 09:32

    A couple of thoughts:

    • If your GUID is auntoincremental and unique, why not let it be the actual Primary Key?

    • On the other hand, you should never take semantical decisions based on programmatic problems: you have a problem with MySQL, not with the design of your DB.

    So, a couple of workarounds here:

    • Creating a trigger that would set the GUID to the proper value once it's inserted. That's a MySQL solution to a MySQL problem, without altering semantics for your schema.

    • Before inserting, start a transaction (make sure auto commit is set to false), find out the latest GUID, increment and insert with the new value. In other words, auto-increment not automatically :P

    0 讨论(0)
  • 2021-01-03 09:32

    If, for some reason, you can't change the identity column to be a primary key, what about manually generating the auto-increment via some kind of SEQUENCE table plus a trigger to query the SEQUENCE table and save the next value to use. Then assign the value to the destination table in the trigger. Same effect. The only question I would have is whether the auto-incremented value is going to make it back thru NHibernate without a re-select of the table.

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