数据库表创建成功后,通常都需要向表中添加约束,常用的约束级创建方式如下:
创建约束
1、主键约束
添加主键约束的表的字段必须有唯一值,而且必须为空。
alter table test add primary key(id)
2、外键约束
表中的一个非主键字段和另一张表的主键子段取值相关联。
创建外键约束:
alter table test add constraint foreignTest foreign key(audit_id) refrences audit_test(id)
可以给外键约束加上 on delete cascade,表示在父表中删除数据时子表对应的数据也被删除。
alter table test add constraint foreignTest foreign key(audit_id) refrences audit_test(id) on delete cascade;
如果加上 on delete set null 则表示父表中删除数据时与子表的数据置空。
alter table test add constraint foreignTest foreign key(audit_id) refrences audit_test(id) on delete set null;
如果加上 novalidate关键字,则表示已经存在的数据不受外键约束,新增加的数据会受外键约束。
alter table test add novalidate constraint foreign key(audit_id) refrences audit_test(id)
3、Check约束
Check约束会检查数据是否符合特定的规则。
alter table test add constraint checkTest check(color in (‘red’,‘yellow’,‘blue’))
4、非空约束
非空约束检查字段不能为空,同时非空约束必须用modify
alter table test modify name constraint nullTest not null
5、唯一约束
唯一约束是字段中的值必须是唯一的,字段可以为空
alter table test add constraint uniqueTest unique(male)