SQL 服务器中 GUID 键和 int 键的索引如何工作?

How does the indexing of GUID keys and int keys in SQL Server work?

是不是我一直在SQL中创建一个实现GUID的table,为此我回顾了这个问题:

What are the best practices for using a GUID as a primary key, specifically regarding performance?

这里的答案告诉我使用一个 GUID 密钥和另一个密钥,但使用 Identity,因此:

CREATE TABLE dbo.MyTable
(PKGUID UNIQUEIDENTIFIER NOT NULL,
 MyINT INT IDENTITY (1,1) NOT NULL,
 .... add more columns as needed ......)

ALTER TABLE dbo.MyTable
ADD CONSTRAINT PK_MyTable
PRIMARY KEY NONCLUSTERED (PKGUID)

CREATE UNIQUE CLUSTERED INDEX CIX_MyTable ON dbo.MyTable (MyINT)

我的问题是:当它说我们已经在使用 GUID 时,为什么还要使用 int 密钥?

混淆源于答案中 "key" 一词的多重含义;也就是说,答案是:

if you want to have your PKGUID column as your primary key (but not your clustering key), and another column MYINT (INT IDENTITY) as your clustering key...

我会把它改成(更改 粗体):

if you want to have your PKGUID column as your primary key (but not your clustered index), and another column MYINT (INT IDENTITY) as your clustered index...

要点是,默认情况下,PRIMARY KEY 建立在聚簇索引上(除非您另外指定);然后聚集索引包含在所有其他索引中,在 GUID 作为聚集 PK 的情况下,这可能是一个重要的性能瓶颈。您发布的代码是一种妥协;它满足 "need" 具有主键的 GUID,同时聚集在较小的列值上(这可以提高性能)。

这并不理想,但它可能是一种非常有用的方法。如果您想详细了解键和索引之间的区别,这里有一些有用的链接:

What is the difference between a primary key and a index key https://itknowledgeexchange.techtarget.com/sql-server/difference-between-an-index-and-a-primary-key/ When should I use primary key or index?