数据完整性约束(2)—— 用户定义完整性

一.MySQL支持哪几种用户定义完整性?

.MySQL支持三种用户自定义完整性:非空约束,check约束,触发器约束。

二.非空约束

 采用关键字:not  null来定义非空约束

 例子:

create table tb(
tb_id int not null 
);

 

三.check约束

3.1对于列的check约束

语法:在列的定义后面使用check(sql语句)

例子:

create table tb(
tb_id int not null check(tb_id<100000)
);

接下来我们来进行一次操作,插入一个大于100000的值100001并查询:

insert into tb values(100001);
select tb_id from tb;

奇怪的是100001竟然插入到了数据库中,原来MySQL只是对check约束做了分析,并没有实质性的操作约束。

3.2对表实行check约束

 在表的末尾进行定义,语法:

create table tb(
tb_id int,
tb_text varchar(20),
check(tb_id in(10,20,30,50))
);

 同样对表的check约束也是一个空壳罢了。

四.删除约束

 使用关键字:alter table 表名  drop  约束类型【外键 | 索引】约束名  |【主键】

 删除主键例子:

alter table tb drop primary key;

猜你喜欢

转载自www.cnblogs.com/SAM-CJM/p/9704999.html