【问题标题】:primary key and index concept主键和索引概念
【发布时间】:2010-07-20 15:16:31
【问题描述】:

我创建一个列作为主键,这会自动创建索引吗?还是我需要明确创建索引。我假设主键也维护索引

【问题讨论】:

  • 取决于数据库实现——你对什么数据库感兴趣??

标签: indexing


【解决方案1】:

在 SQL Server 中创建主键将在该列上创建唯一聚集索引。 或者更具体地说来自here

注意 PRIMARY KEY 约束创建 如果没有,则自动聚集索引 聚集索引已存在于 表和非聚集索引不是 创建 PRIMARY 时指定 KEY 约束。

【讨论】:

  • 所以不需要显式地创建索引?
  • 如果您还没有在表上指定聚集索引,并且您没有告诉它使用 diff 非聚集索引,那么将自动为您创建索引和约束。 (仅供参考,聚集索引对数据的顺序进行物理排序,因此每个表只能有一个聚集索引)
  • 另一个注意你提到索引(复数)。创建主键会创建单个聚集索引,它不会神奇地确定需要索引的位置并为您创建它们。您可能会发现还需要添加一些非聚集索引来提高性能。
【解决方案2】:

这应该会清除一些空气。

--creating a table without any primary key
CREATE table understanding_indexes
 (P_Id int,
 LastName varchar(255),
 FirstName varchar(255),
 Address varchar(255),
 City varchar(255)
 )
 --
 --checking for indexes
 sp_helpindex understanding_indexes

输出

 The object 'understanding_indexes' does not have any indexes, or you do not have permissions.

--ADDING A NOT NULL CONSTRAINT
ALTER TABLE UNDERSTANDING_INDEXES 
ALTER COLUMN P_Id INTEGER
NOT NULL

--ADDING A PRIMARY KEY Constraint, can only be done on column which are not null.
ALTER TABLE UNDERSTANDING_INDEXES
ADD PRIMARY KEY (P_Id)

sp_helpindex understanding_indexes

输出

PK__understa__A3420A5702084FDA  clustered, unique, primary key located on PRIMARY  P_Id

总体而言,只要在表上添加主键约束,它就会自动在表上添加聚簇索引。

此插图适用于 SQL Server 2008 R2。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2018-10-05
    • 2013-08-26
    相关资源
    最近更新 更多