何时在 SQL Server 中使用 GUID
可能的重复:
GUID 与 INT IDENTITY
我时不时地看到一个使用 GUID 的系统,我问自己有多少这会影响性能。我曾经在一个到处使用 GUID 的系统上工作过,它是由一位“高级开发人员”编写的,他总是说这是最好的选择等等。我运行了多次测试来检查 GUID 与自动增量的性能,自动增量获胜者是每个查询秒数...
我想知道在什么情况下应该使用 GUID 而不是多个主键/自动增量。
Possible Duplicate:
GUID vs INT IDENTITY
Every now and then I see a system using GUIDs and I ask myself how much this will impact the performance. I once worked on a system that used GUIDs everywhere, it was written by a 'senior developer' and he always said that it was the best option etc. I ran multiple test to check the performance of GUIDs vs auto increment, auto increment won by seconds per query...
I was wondering in what situations I should use GUIDs instead of multiple primary keys/auto increment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于这个问题,有大量的争论/意见/答案,其中一些是关于 SO 的,如果你用 Google 搜索的话,还有更多。
There are tons of debates/opinions/answers for this question around, some here on SO and many many more if you Google for it.
Guid(MSSQL 中的唯一标识符)非常适合键,具有以下优点:
1) 您可以在将对象插入数据库之前自行创建键。这允许您创建第 N 个记录的主详细信息(外键引用),而无需首先询问数据库下一个主记录键是什么。
2) 您可以为每个记录系统范围内的任何记录创建唯一键,这对于使用实体类层次结构的 ORM 数据库很有用。
3)您可以对引导进行硬编码以识别特定记录。示例可能是主“根”用户记录、主“机构”机构记录(如果您创建公司/机构层次结构)、预定义查找(例如性别、安全角色)。
关于优化,是的,使用任何普通的键 GUID 都会减慢数据库的速度,但您可以使用数据库优化的 GUID(您必须在 google 上搜索)。本质上,数据库优化的 guid 使 guid 更加连续,但保留了足够的随机部分以保持它们的唯一性。
Guids (uniqueidentifier in MSSQL) are good for keys offering these advantages:
1) You can create the key yourself before inserting an object into the database. This allows you to create master detail of records (foreign key references) of the Nth without first asking the database what the next master record key will be.
2) You can create unique keys per any record system wide, which use useful for ORM databases that use a class hierarchy for entities.
3) You can hardcode guids which to identify specific records. Examples might be master "root" user record, master "agency" agency record (if you create an company/agency hierarchy), predefined lookups (like gender, security role).
About optimization, yes using any normal guids for keys will slow down your database, but you can use database optimized guids (something you'll have to google for). Essentially a database optimized guid makes a guid more sequential, but preserves enough of the random part to keep them unique.