sql - sql server中唯一主键和复合主键的区别

标签 sql sql-server primary-key unique-constraint

我想知道 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/

相关文章:

使用 LEFT JOIN 的 MySQL 查询,其中第二个表具有 2 部分主键

php - spatie/laravel-medialibrary 更改主键

sql - 公共(public)表表达式有什么用?

mysql - 在 MySQL 中连接父/子节点表时出现问题 - 减少结果集

sql - TSQL : Howto add a char to a select statement

sql - 如何将 SQL Azure 数据库和服务总线添加到虚拟网络?

sql - 使用时间戳查询 MySQL 数据库

mysql - 如何不喜欢MySQL中的许多项目?

sql-server - 在 SQL Server 2012 上还原 SQL Server 2000 备份

mysql - 如何将一条记录插入到以用户 ID 作为外键的表中