在数据库的建表过程中,我们创建主键的原因主要是唯一标识属性列。在SQLServer中,表的主键默认为表的CLUSTERED INDEX,所以主键有提高查询效率的作用。 如果表没有主键(更或者这个地方说成是CLUSTERED INDEX),那么即使为表创建的NONLUSTERED Index,在查询的时候,SQLServer还是会走表扫描。因此,为表创建一个Primary Key就显得十分重要。
至于,搂主提到的为什么要设计为组合Primary Key,我想的话,可能单独的字段不能唯一标示一个元组,而几个字段组合起来可以唯一标识,故而采用组合Primary Key的方式。 谢谢!
至于,搂主提到的为什么要设计为组合Primary Key,我想的话,可能单独的字段不能唯一标示一个元组,而几个字段组合起来可以唯一标识,故而采用组合Primary Key的方式。 谢谢!
use test
gocreate table dbo.Test
(
id int identity(1,1)
,IndexKey int NOT NULL
,PrimaryKey int NOT NULL
,name nvarchar(10)
)
GO
declare @i int
,@j int
select @i=0
,@j=10000while @i<@j
begin insert dbo.Test(IndexKey,PrimaryKey,name)
select @i,@i+12,'Test'
SET @i=@i+1
END
GOcreate nonclustered index ix_Test_IndexKey on dbo.Test
(
IndexKey asc
)
GO
select IndexKey,name,PrimaryKey
from dbo.Test
/*
SQLSerever的查询分析器走Table Scan
*/
GO
ALTER TABLE dbo.test
add constraint PK_Test Primary key
(
IndexKey asc
)
GO
select IndexKey,name,PrimaryKey
from dbo.Test/*
SQLSerever的查询分析器CLUSTERED Index Scan,那么主键对SQLServer的查询就显得很明显了。
*/
我一般是每个表就有一个唯一标识列(一般都是id int identity(1,1) ),将其设为主键。2.在SQL查询效率上 复合主键和单主键 都是一样。