我想知道 SQL Server 中的唯一键和复合主键有什么区别。
根据 w3c 学校:
The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
我们可以使用以下方法创建复合主键:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)
对于复合主键语法:
CREATE TABLE Persons
(
P_Id int,
C_Id int,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
Primary Key (P_Id,C_Id)
);
最佳答案
UNIQUE 约束唯一标识数据库表中的每条记录。这为一列或一组列的唯一性提供了保证。我们可以用这个定义(指向)一行。
默认情况下, PRIMARY KEY 具有 UNIQUE 约束。
而在某些表中,不会有任何具有唯一值的列来定义行。在这种情况下,使用复合键。在这种情况下,两列或更多列组合在一起,因此这种组合是唯一的。
关于sql - sql server中唯一主键和复合主键的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41015034/