概念
约束是作用于表中字段上的规则,用于限制存储在表中的数据,保证数据库中数据的正确性、有效性和完整性。
分类
注意:
1、约束是作用于表中字段上的,可以在创建表/修改表的时候添加约束
2、多个约束之间用空格隔开
3、自动增长(auto_increment)
外键约束
具有外键的表(子表/从表)
外键所关联的表(父表/主表)
1、添加外键语法
create table (表名
字段名 数据类型,
...
[constraint][外键名称] foreign key(外键字段名) references 主表(主表列名)
);
alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名);
2、删除外键约束
alter table 表名 drop foreign key 外键名称;
3、删除/更新行为
alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名) on update 行为 on delete 行为;