SQL 主键
我遇到了 2 个版本的 sql 代码。
--1
CREATE TABLE Location (
Id INTEGER PRIMARY KEY
NOT NULL,
Name TEXT NOT NULL
);
--2
CREATE TABLE Location (
Id INTEGER PRIMARY KEY
NOT NULL
UNIQUE,
Name TEXT NOT NULL
);
在 SQL 中,是否需要指定主键唯一且不为 null?
我总是假设主键是唯一的并且不能为空。
I came across the 2 versions of sql code..
--1
CREATE TABLE Location (
Id INTEGER PRIMARY KEY
NOT NULL,
Name TEXT NOT NULL
);
--2
CREATE TABLE Location (
Id INTEGER PRIMARY KEY
NOT NULL
UNIQUE,
Name TEXT NOT NULL
);
In SQL, is it necessary to specify the primary key to be unique and not null?
I always assumed that the primary key was unique and could not be null.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一张表最多可以有一个主键,但可以有多个唯一键。主键是唯一指定行的列的组合。这是唯一键的特例。一个区别是主键具有隐式 NOT NULL 约束,而唯一键则没有。
A table can have at most one primary key, but more than one unique key. A primary key is a combination of columns which uniquely specify a row. It is a special case of unique keys. One difference is that primary keys have an implicit NOT NULL constraint while unique keys do not.
在主键列上指定“UNIQUE”是多余的 - 作为主键已经确保了这种情况。
Specifying "UNIQUE" on a primary key column is redundant - being the primary key already ensures that will be the case.
UNIQUE 和 NOT NULL 都是不必要的,因为 PRIMARY KEY 意味着两者。
Both UNIQUE and NOT NULL are unnecessary, because PRIMARY KEY implies both.
您的代码是有效的语法。它将创建覆盖同一列的
PRIMARY KEY
和UNIQUE
约束。表具有多个键但不在同一组列上是有正当理由的。一张表只能有一个标记为“主”的键。每个表至少需要一个键,但不需要将键标记为“主”,即使表只有一个键也是如此。
在 SQL Server 中,标记为“主”具有含义(例如
NOT NULL
、创建外键引用时的默认键等),但我更喜欢明确这些事情。大概的目的是让您的表拥有唯一的键,因此我建议您省略PRIMARY KEY
。我进一步建议您为您的UNIQUE
键指定一个明确的名称,例如Your code is valid syntax. It will create both a
PRIMARY KEY
and aUNIQUE
constraint covering the same column.There are legitimate reasons for a table having more than one key but not on the same set of columns. A table may only have one key flagged as "primary". Every table requires at least one key but there is no requirement to flag a key as "primary", even when a table has only one key.
In SQL Server, flagging as "primary" has implications (e.g.
NOT NULL
, the default key when creating a foreign key reference, etc) but I prefer to be explicit about such things. Presumably the intention is for your table to have a sole key so I suggest you omit thePRIMARY KEY
. I further recommend you give yourUNIQUE
key an explicit name e.g.