sql 主键和外键
With a table created with this command:
使用通过此命令创建的表:
CREATE TABLE people (
age INT NOT NULL,
name CHAR(20) NOT NULL
);
We can insert an item more than once.
我们可以多次插入一个项目。
And in particular, we can have columns that repeat the same value.
特别是,我们可以有重复相同值的列。
We can force a column to have only unique values using the UNIQUE
key constraint:
我们可以使用UNIQUE
键约束将一列强制为唯一值:
CREATE TABLE people (
age INT NOT NULL,
name CHAR(20) NOT NULL UNIQUE
);
Now if you try to add the ‘Flavio’ twice:
现在,如果您尝试两次添加“ Flavio”:
INSERT INTO people VALUES (37, 'Flavio');
INSERT INTO people VALUES (20, 'Flavio');
You’d get an error:
您会得到一个错误:
ERROR: duplicate key value violates unique constraint "people_name_key"
DETAIL: Key (name)=(Flavio) already exists.
A primary key is a unique key that has another property: it’s the primary way we identify a row in the table.
主键是具有另一个属性的唯一键:这是我们在表中标识行的主要方式。
CREATE TABLE people (
age INT NOT NULL,
name CHAR(20) NOT NULL PRIMARY KEY
);
The primary key can be an email in a list of users, for example.
例如,主键可以是用户列表中的电子邮件。
The primary key can be a unique id
that we assign to each record automatically.
主键可以是我们自动分配给每个记录的唯一id
。
Whatever that value is, we know we can use it to reference a row in the table.
无论该值是多少,我们都知道可以使用它来引用表中的一行。
sql 主键和外键