数据库 约束 【vaynexiao】

建议用以下方式创建约束,一旦出现违反约束错误,可以直接显示出约束名,很有利于排查错误
create table product(
    pid numeric(5),
    pname varchar(20),
    pdate varchar(200) constraint nn_pdate_product not null,
    location char(30) default ‘北京’,
    fkdeptno numeric(5),
    constraint uk_pname_product unique(pname),
    constraint pk_pid_product primary key(pid),
    constraint ck_pid_product check(pid>10000 AND pid<9999),
    constraint fk_fkdeptno_product foreign key (fkdeptno) references dept(deptno)
);
not null(nn)
创建表时定义约束:比如在字段score number(5,0)后面直接添加not null 为字段级约束;
或者在建表时字段最后添加constraint usercode_nn not null为表级约束,可设置多个列的组合为约束对象;
修改约束:after table pcmc_user modify(usercode varchar(50)not null)
删除约束:alter table pcmc_user drop constraint constraint_name
unique key(uk)
可出现多次null值,因为null不在约束范围之中
创建表时直接定义唯一性约束:constraint usercode_uk unique(email)
修改唯一性约束:alter table emp add constraint emp_name_uk unique(card);
其他操作同 not null
primary key(pk)
创建表时直接定义主键约束:constraint usercode_pk primary key(非空+唯一)
修改主键约束:alter table emp add constraint usercode_pk primary key(id);
check key(ck)
constraint ck_age_emp check(age between 0 and 100)  --添加检查约束
foreigh key(fk)
外键约束是定义在子表上:constraint fk_usercode foreign key(deptno) references dept(deptno) [on delete cascade]
–on delete cascade级联删除:给子表添加这样的属性后,父表删除有关联的数据时,子表关联的数据会自动删除
若不希望直接级联删除,可设置关联记录数据为null,on delete set null
–on delete set null级联更新:给子表添加这样的属性后,父表删除有关联的数据时,子表关联的数据会自动set null
alter table emp add constraint emp_deptno_fk foreign key(deptno) references dept(deptno);
有关联时这样强制删除:drop table emp cascode constraint [purge];
–子表还在检查约束:constraint ename_ck check(enamein(‘男’,‘女’))
–如果要作为子表外键关联的父表列,这列必须设置为唯一约束或主键约束
–删除父表数据之前必须断开与子表的关联,否则无法删除
primary key 和 unique key 的区别:
1,主键约束只能一个(可以联合主键),但唯一约束可以多个
2,主键不能为空,唯一约束可以为空

发布了75 篇原创文章 · 获赞 106 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/vayne_xiao/article/details/105321104