约束
约束的作用
-
面临的问题
-某列必须有值且唯一
-某列的取值受到另一列取值的限制 -
数据库提供的解决方法
-限制无效的数据进入到表中
-数据库层面的"安检"
约束的类型
约束名 | 意思 |
---|---|
primary key | 主键约束 |
unique key | 唯一键约束 |
not null | 非空约束 |
references foreign key | 外键约束 |
check | 检查约束 |
复制代码
1
2
3
4
5create table test( c1 number constraint test_c1_pk primary key ,c2 number ); insert into test values (1,1);
主键约束(表级约束):不能为空
,唯一
复制代码
1
2
3alter table test add constraint test_c3_pk primary key (c2);
给存在的表增加约束,语法形式跟表级约束一样
非空约束(not null)
- 不允许将该列的值置为空
- 只有列级约束的形式
colname datetype not null
唯一键约束 - 列级约束
复制代码
1
2
3
4
5
6
7create table test ( c1 number(3) constraint c1pk primary key , c2 number(2) constraint c2uk unique not null , c3 number(2) constraint c3uk unique , c4 number(2) constraint c4nn not null );
然后我们插入
复制代码
1
2insert into test(c1,c2) values (1, 1 );
这个肯定是不行的,因为c4列
约束也是非空
要这样才行,c3可以不给值
复制代码
1
2insert into test(c1,c4,c2) values (1, 1 ,1);
但是如果再次执行
复制代码
1
2insert into test(c1,c4,c2) values (1, 1 ,1);
又会报错,因为c1和c2是不允许有重复值
的,但是null确可以重复(c3)
复制代码
1
2
3
4
5
6
7
8
9create table test( c1 number(3) constraint c1pk primary key , c2 number(3) , c3 number(3), constraint c23uk unique (c2,c3) ); insert into test values (1,null,1); insert into test values (1,null,null);
联合约束
insert into test values (1,null,1);
可以完成,但是insert into test values (1,null,null);
不能完成,因为不能使c2,c3相等.
cheak约束
复制代码
1
2
3
4
5create table test( c1 number constraint c1pk primary key , c2 number constraint c2ck check(c2>100) )
复制代码
1
2
3
4
5
6
7create table test( c1 number constraint c1pk primary key , c2 number, c3 number, constraint c23ck check((c2+c3)>100) );
联合约束↑
复制代码
1
2
3
4
5create table test( c1 number constraint c1ck check ( c1 in(1,3,5) ) ); insert into test values ('1');
复制代码
1
2
3
4
5
6
7
8alter table parent add constraint c1pk primary key (c1); create table child ( c1 number(2) constraint c11pk primary key , c2 number constraint c2fk references parent(c1)); ; insert into parent values (1); insert into child values (10,1);
父子表,必须parent里面有1,child才能传入1
外键约束的关键字
- foreign key
-用表级约束定义外键时使用该关键字 - references
-表示引用父表中的某列 - on delete cascade
-级联删除,删除父表的记录前,先删除子表里的相关记录 - on delete set null
-删除父表的记录前,先将子表中外键列的相关值置空
由上述介绍可知:
on delete cascade
会将子表关于发表要删除的信息先行删除相关行
on delete set null
会将子表关于发表要删除的信息先行将相关行的相关列置为空
外键约束
- 保证一对多关系
- 通过外键(FK)可以与同一张表的主键(PK)或唯一键(UK)建立引用关系,也可以与不用表的主键(PK)或唯一键(UK)建立引用关系
- 外键的取值必须匹配父表中已有的值或空值
最后
以上就是活力发带最近收集整理的关于sql约束约束的全部内容,更多相关sql约束约束内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复