Mysql约束

常见的约束有五大类型:

唯一性约束 unique
非空约束 not null
主键约束 primary key
外键约束 foreign key
检查约束 check

唯一性约束 unique

对相应的列建立索引,是唯一性索引,用于提升查询效率,该列要求值唯一。
建表时设置
create table t_user(id int,name varchar(20) unique,sex char(1),phone varchar(11));
建表后添加,uk_stu_name为约束的名字
alter table student add constraint uk_stu_name unique(name);

非空约束 not null

要求改列的值不能是null值,必须显示的插入或者更新一个值非空约束只能是列级约束
建表时设置
create table t_user(id int,name varchar(20) unique,sex char(1) not null,phone varchar(11));
建表后添加
alter table student modify name varchar(30) not null;

主键约束 primark key

要求改列的值是非空且唯一的。
建表时设置
create table t_user(id int primary key auto_increment,name varchar(20) unique,sex char(1) not null,phone varchar(11));
建表后添加
alter table student add constraint pk_stu_name primary key (id);

外键约束 foreign key

用于两表之间建立关系的。在从表中建立一个字段列添加外键约束引用主表的主键值。

建表时设置,t_emp 表中的deptid 属性参照t_dept 表中的id列,t_emp为从表,t_dept为主表
create table t_emp (id int primary key auto_increment,name varchar(200),sex char(1),salary double(10,2),deptid int,foreign key(deptid) references t_dept(id) );
建表后添加
alter table t_emp add constraint fk_emp_dept foreign key (deptid) references t_dept(id);

检查约束 check

mysql不支持 Oracle支持的
create table t_stu(id int primary key auto_increment,name varchar(20),age int check (age>20));

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值