你能在 MySql 中使用自动增量而不是主键吗

我使用 GUID 作为我所有其他表的主键,但我有一个需要递增数字的要求.我试图用自动增量在表中创建一个字段,但 MySql 抱怨它需要成为主键.

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 the auto increment but MySql complained that it needed to be the primary key.

我的应用程序使用 MySql 5,nhibernate 作为 ORM.

My application uses MySql 5, nhibernate as the ORM.

我想到的可能解决方案是:

Possible solutions I have thought of are:

  • 将主键更改为自动递增字段,但仍将 Id 作为 GUID,因此我的应用程序的其余部分是一致的.

  • change the primary key to the auto-increment field but still have the Id as a GUID so the rest of my app is consistent.

创建一个包含 GUID 和自增字段的复合键.

create a composite key with both the GUID and the auto-increment field.

我目前的想法倾向于复合键的想法.

My thoughts at the moment are leaning towards the composite key idea.

行 ID(主键)是当前的 GUID.我想添加一个自动递增的 INT 字段,以便它是人类可读的.我只是不想改变应用程序中将 GUID 作为主键的当前标准.

The Row ID (Primary Key) is the GUID currently. I would like to add an an INT Field that is Auto Incremented so that it is human readable. I just didn't want to move away from current standard in the app of having GUID's as primary-keys.

推荐答案

GUID 值旨在跨表甚至数据库是唯一的,因此,使 auto_increment 列主索引并为 GUID 创建 UNIQUE 索引

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

相关文章