数据库:主键,集群或非集群。

时间:2022-10-17 22:47:19

I am creating a database in SQL server 2008,

我正在SQL server 2008中创建一个数据库,

CREATE TABLE Users
(
    U_Id INT NOT NULL
    FirstName VARCHAR(50) NOT NULL,
    LastName VARCHAR(50) NOT NULL,
    Email VARCHAR(200)
    Password VARCHAR(50)
)

I want to make U_Id the primary key. I would like to ask what is the difference between

我要将U_Id作为主键。我想问一下有什么区别。

 CONSTRAINT pk_UserID PRIMARY KEY (U_Id)

this

 CONSTRAINT pk_UserID PRIMARY KEY CLUSTERED (U_Id)

and this

CONSTRAINT pk_UserID PRIMARY KEY NONCLUSTERED (U_Id)

When to use each?

何时使用?

I read some article but it is still unclear to me. Can someone give me a quick explanation?

我读了一些文章,但还是不清楚。谁能给我一个快速的解释吗?

1 个解决方案

#1


37  

The following statement:

下面的语句:

CONSTRAINT pk_UserID PRIMARY KEY (U_Id)

Is the same as this one:

和这个是一样的:

CONSTRAINT pk_UserID PRIMARY KEY CLUSTERED (U_Id)

You can only have the table data physicality ordered by one of the indexes, and by default that index is the one used for the primary key (the primary key unique constraint is always supported by an index).

您只能让一个索引为表数据的物理性质排序,默认情况下,索引是主键使用的索引(主键惟一约束总是由索引支持)。

If you want to leave the order of the table data to be stored according to some other index then you should create the primary key with:

如果您想让表数据的顺序按照其他索引存储,那么您应该创建主键:

CONSTRAINT pk_UserID PRIMARY KEY NONCLUSTERED (U_Id)

And then create the clustered index with:

然后用:

CREATE CLUSTERED INDEX ix_Email ON Users (Email); 

#1


37  

The following statement:

下面的语句:

CONSTRAINT pk_UserID PRIMARY KEY (U_Id)

Is the same as this one:

和这个是一样的:

CONSTRAINT pk_UserID PRIMARY KEY CLUSTERED (U_Id)

You can only have the table data physicality ordered by one of the indexes, and by default that index is the one used for the primary key (the primary key unique constraint is always supported by an index).

您只能让一个索引为表数据的物理性质排序,默认情况下,索引是主键使用的索引(主键惟一约束总是由索引支持)。

If you want to leave the order of the table data to be stored according to some other index then you should create the primary key with:

如果您想让表数据的顺序按照其他索引存储,那么您应该创建主键:

CONSTRAINT pk_UserID PRIMARY KEY NONCLUSTERED (U_Id)

And then create the clustered index with:

然后用:

CREATE CLUSTERED INDEX ix_Email ON Users (Email);