mysql四种约束_MySQL中四种约束简述。

一.数据的完整性

域完整性

实体完整性

引用完整性

二.约束

1. 非空约束 not null

insert into teacher(id,sex,birthday)

values(1,'male','2018-5-5')

会报错,因为name项有非空约束

取消非空约束:

alter table teacher modify name vachar(10);

如果要继续为name加上非空约束,应该先删掉name的值,然后再执行以下语句,否则会报错。

alter table teacher modify name varchar(10) not null;

或者:

alter table teacher change name name varchar (10) not null;

2. 唯一约束 unique

create table test_unique(

id int(10),

name varchar(32) not null,

email varchar(128) unique

);

添加数据

insert into test_unique values(1,'zmt','www.qwe@qwe.com')

取消唯一性约束:

语法:alter table 表名 drop index 字段名;

alter table test_unique drop index email;

建表后添加唯⼀性约束:

语法:alter table 表名 add unique(字段名)

alter table test_unique add unique(id);

3.主键约束

create table test3_primary(

id int not null,

name varchar(50) not null,

primary key(id,name)

);

insert into test3_primary values(1,'abc')

删除主键约束:

语法:alter table 表名 drop primary key;

alter table test3_primary drop primary key;

建表后添加主键约束:

语法:alter table 表名 add primary key(字段名)

alter table test3_primary add primary key(id) ; --将字段设置为主键

4. 默认值约束 default

create table test1_default(

id int not null,

name varchar(50) not null DEFAULT 'abc'

);

插⼊数据的时候,如果不写⼊name的值,则默认显示填入abc

删除默认值约束:

语法:alter table 表名 change 字段 字段 字段类型 not null

alter table test1_default change name name varchar(50) not null

建表后添加默认值约束:

语法:alter table 表名 modify 列名 列类型 not null default ‘默认值’;

alter table test1_default modify name varchar(50) not null default 'abc';

5.外键约束

建表的同时建外键

create table emp(

.......

foreign key(外键字段) references dept(deptno)

)

建立表之后添加外键

alter table emp add foreign key(deptno) references dept(deptno)

删除外键:

语法:alter table 表名称 drop foreign key 外键名称;

例:alter table empA drop foreign key empa_ibQk_1;

注意:如果没有在建表的时候标明外键名称,可以通过:

show create table 表名 进⾏查看外键名称;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值