mysql提供的六种约束_MySQL中的六个约束

主键约束 primary key:一个表中只能有一个主键,主键值不能为空,不能重复

设置主键约束:1 在创建表时就设置好主键约束

create table person(id int primary key);

或  create table person(id int ,name char(10),primary key(id));

2 通过修改表中列的属性来设置主键约束

alter table person add primary key(id);

或  alter table person modify id int primary key;

设置联合主键:1:在创建时就设置为联合主键约束

create table person(id int,name char(10),primary key(id,name));

2:修改列的属性设置联合主键约束

alter table person add primary key(id,name);

不同记录的联合主键的列值不能同时相同,可以分别相同,不能同时为空

删除主键约束:alter table person drop primary key;

递增约束 auto_increment:设置为自动递增的列,自己没给他添加值,系统会自动给他赋值,一般把主键设为递增约束

create table student(id int primary key auto_increment);

唯一约束 unique:设置为唯一约束的列值不能重复

设置唯一约束:  1 在创建表时就设置好唯一约束

create table person(id int unique);

或  create table person(id int ,name char(10),unique(id));

2 通过修改表中列的属性来设置唯一约束

alter table person add unique(id);

或  alter table person modify id int unique;

设置联合唯一约束:1:在创建时就设置为联合唯一约束

create table person(id int,name char(10),primary key(id,name));

2:修改列的属性设置联合唯一约束

alter table person add unique(id,name);

不同记录的联合唯一约束的列值不能同时相同,可以分别相同,不能同时为空

删除主键约束:alter table person drop unique;

默认约束 default:设置某个列在没有记录时使用默认值

create table person (id int,name char(10) default 'zhangsan');

非空约束 not null:非空约束的列值不能为空

create table person(id int,name char(10) not null);

外键约束 foreige key   references:副表被约束的列值从主表约束列值中选择,主表约束的列值被副表列值使用时,这个主表的列值不能被删除。主表的列必须是主键;

create table person(id int primary key);

create table student(id int,foreign key(id) references person(id));

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值