简体   繁体   English

在SQL Server设计中是否必须使用“主键”?

[英]Are 'Primary Keys' obligatory in SQL Server Design?

Observe the following table model: 观察下表模型:

CREATE TABLE [site].[Permissions] (
    [ID]     INT REFERENCES [site].[Accounts]( [ID] ) NOT NULL,
    [Type]   SMALLINT NOT NULL, 
    [Value]  INT NULL
);

The site.Accounts->site.Permissions is a one-to-many relationship so 'ID' cannot be made a primary key due to the uniqueness that a PK imposes. site.Accounts-> site.Permissions是一对多关系,因此由于PK的唯一性,不能将“ ID”作为主键。

The rows are selected using a WHERE [ID] = ? 使用WHERE [ID] = ?选择行WHERE [ID] = ? clause, so adding a phoney IDENTITY column and making it the PK yields no benefit at the cost of additional disk space. 子句,因此添加一个电话IDENTITY列并使其成为PK不会带来任何好处,但会增加磁盘空间。

Its my understanding that the targeted platform - SQL Server (2008) - does not support composite PKs. 据我了解,目标平台-SQL Server(2008)-不支持复合PK。 These all add up to my question: If a Primary Key is not used, so something wrong? 这些全都加到我的问题上: 如果不使用主键,那有什么问题吗? Or could something be more right? 还是有些事情更正确?

Your understanding is not correct, SQL Server does support composite primary keys! 您的理解是不正确的,SQL Server确实支持复合主键!

The syntax to add one would be 添加一个的语法是

ALTER TABLE  [site].[Permissions] 
ADD CONSTRAINT PK_Permissions PRIMARY KEY CLUSTERED (id,[Type])

Regarding the question in the comments "What is the benefit of placing a PK on the entire table?" 关于评论中的问题“在整个桌子上放置PK有什么好处?”

I'm not sure from your description though what the PK would need to be on. 根据您的描述,我不确定PK是否需要启用。 Is it all 3 columns or just 2 of them? 是全部3列还是仅其中2列? If it's on id,[Type] then presumably you wouldn't want the possibility that the same id,[Type] combo could appear multiple times with conflicting values. 如果在id,[Type]那么您可能不希望同一id,[Type]组合可能出现多次但值冲突。

If it is on all 3 columns then to turn the question around why wouldn't you want a primary key? 如果在所有3列中都存在,那么要解决这个问题,为什么不想要主键呢?

If you are going to have a clustered index on your table you could just make that the primary key. 如果您要在表上具有聚簇索引,则可以将其设为主键。 If say you made a clustered index on the id column only SQL Server would add in uniqueifiers anyway to make it unique and your columns are so narrow ( int , smallint , int ) this just seems a pointless addition. 如果说您在id列上创建了聚集索引,则无论如何SQL Server都将添加唯一标识符以使其唯一,并且您的列是如此狭窄( intsmallintint ),这似乎毫无意义。

Additionally the query optimiser can use unique constraints to improve its query plans (though might not apply if the only queries on that table really are WHERE [ID] = ? ) and it would be pretty wasteful to allow duplicates that you then have to both store and filter out with DISTINCT . 另外,查询优化器可以使用唯一的约束来改进其查询计划(尽管如果该表上的唯一查询实际上是WHERE [ID] = ?则可能不适用),并且如果允许重复存储然后又要存储两个重复项,则将非常浪费。并使用DISTINCT过滤掉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM