6

为什么 aspnet_users 使用 guid 作为 id 而不是递增 int?

还有没有理由在其他表中使用它作为主键?感觉有点奇怪,因为我知道我过去使用过的大多数应用程序都只是使用普通的 int 系统。

我也即将开始使用这个 id 来匹配一个扩展的详细信息表以获取额外的用户首选项等。我也在考虑使用一个带有 guid 和一个 int 的链接表,但决定我不认为我实际上需要将用户 ID 作为公共 int。

虽然我想拥有 int (感觉更容易进行用户查找等 stackoverflow.com/users/12345/user-name ),因为我只需要用户名,我认为我不需要携带这个项目,并在我需要查找用户 int 时导致查找的额外复杂性。

感谢您提供任何帮助。

4

2 回答 2

13

它确保了跨断开系统的唯一性。任何可能需要与另一个以前未连接的数据存储交互的数据存储都可能会遇到冲突——例如,它们都用于int识别用户,现在我们必须经历一个复杂的解决过程来为冲突的 ID 选择新的 ID,并相应地更新所有引用。

在 SQL 中使用标准唯一标识符(使用 newid())作为主键的缺点是 GUID 不是连续的,因此在创建新行时,它们会插入到物理数据库页面中的某个任意位置,而不是附加到结尾。对于具有任何实质性插入率的系统,这会导致严重的页面碎片。可以改用 newsequentialid() 来纠正它。我在这里更详细地讨论了这一点。

一般来说,最好的做法是使用 newsequentialid() 作为您的 GUID 主键,或者不使用 GUID 作为主键。您始终可以拥有一个存储 GUID 的二级索引列,您可以使用它来保持引用的唯一性。

于 2009-11-04T21:16:44.333 回答
5

GUIDs as a primary key are quite popular with certain groups of programmers who don't really (don't want to or don't know to) care about their underlying database.

GUIDs are cool because they're (almost) guaranteed to be unique, and you can create them "ahead of time" on the client app in .NET code.

Unfortunately, those folks aren't aware of the terrible downsides (horrendous index fragmentation and thus performance loss) of those choices when it comes to SQL Server. Lots of programmer really just don't care one bit..... and then blame SQL Server for being slow as a dog.

If you want to use GUIDs for your primary keys (and they do have some really good uses, as Rex M. pointed out - in replication scenarios mostly), then OK, but make sure to use a INT IDENTITY column as your clustering key in SQL Server to minimize index fragmentation and thus performance losses.

Kimberly Tripp, the "Queen of SQL Server Indexing", has a bunch of really good and insightful articles on the topic - see some of my favorites:

and basically anything she ever publishes on her blog is worth reading.

于 2009-11-04T22:25:21.630 回答