问题描述
使用示例更容易。我有两个表:书和章。两者都有Title和Id列。章还有一个Book列,它是Books.Id的外键。 Books.Title是唯一的(我不想要两本具有相同标题的书)。
It's easier with an example. I have two tables: Books and Chapters. Both have Title and Id columns. Chapters also has a Book column which is a foreign key to Books.Id. Books.Title is unique (I don't want two books with the same title).
现在我的问题是定义Chapter.Title的唯一性。我想要它是唯一的只要Books.Id是相同的。因此,一本书可能没有两个具有相同标题的章节,但两个不同的书在一章中可能具有相同的标题。
Now my problem is defining Chapter.Title uniqueness. I want it to be unique as long as Books.Id is the same. So that one book may not have two chapters with the same title but two different books may have the same title in a chapter.
这是否可能在SQL Server 2008上?如何?
Is this possible on SQL Server 2008? How?
推荐答案
UNIQUE CONSTRAINT或UNIQUE索引。
UNIQUE CONSTRAINT or UNIQUE index. Either one will do.
ALTER TABLE dbo.MyTable WITH CHECK ADD
CONSTRAINT UQ_MyTable_BookTitle UNIQUE (BookID, Title)
或
CREATE UNIQUE INDEX IXU_MyTable_BookTitle ON dbo.MyTable (BookID, Title)
这篇关于如何在SQL Server 2008中的关系范围中指定一个唯一的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!