mysql:字段约束
为了确保数据的完整性和唯⼀性,关系型数 据库通过约束机制来实现目的
约束类型
| 约束 | 名称 | 作用 |
|---|---|---|
| unique | 唯一性约束 | 值不可重复 |
| not null | 非空约束 | 值不可为空 |
| default | 默认值约束 | 写入数据时,空值设置为value |
| primary key | 主键约束 | 表的标志性字段,值不可重复,不可为空 |
| foreign key | 外键约束 | 外键是另一表的主键,常用来和其他表建立联系 |
注:
- 主键:一张表只能有一个主键,主键可以是一个字段,也可以是多个字段(联合主键,复合主键)
- 外键:必须是另一表主键,且必须与主键类型一致、编码一致
添加约束
创建表时,字段末添加
create table <表名称>(
<字段1> <类型> unique,
<字段2> <类型> not null,
<字段3> <类型> default <默认值>,
<字段4> <类型> primary key
);
- 不支持添加foreign key
创建表时,字段末添加
create table stu(
<字段> <类型>,
...
<字段> <类型>,
constraint <约束起名> unique(字段名),
constraint <约束起名> not null(字段名),
constraint <约束起名> primary key(字段名),
constraint <约束起名> foreign key(字段名) references <表名>(字段名)
);
修改表结构添加
alter table stu add constraint <约束起名> unique(字段名);
alter table stu add constraint <约束起名> not null(字段名);
alter table stu add constraint <约束起名> primary key(字段名);
alter table stu add constraint <约束起名> foreign key(字段名) <表名>(字段名);
查看约束
show keys from <tbname>;
删除约束
drop <constraint name> on <tbname>;

浙公网安备 33010602011771号