1.主键约束:primary key
alter table 表名 modify 字段名 数据类型 primary key; #添加主键约束
alter table 表名 drop primary key; #删除主键约束
2.非空约束:not null
alter table 表名 modify 字段名 数据类型 not null; #添加非空约束
alter table 表名 modify 字段名 数据类型; #删除非空约束
3.唯一约束:unique
alter table 表名 add unique(字段名); #添加唯一约束
alter table 表名 drop index 字段名; #删除唯一约束
4.默认约束:default
alter table 表名 modify 字段名 数据类型 default 默认值; #添加默认约束
alter table 表名 modify 字段名 数据类型; #删除默认约束
5.外键约束:foreign key
alter table 表名 add constraint 外键名 foreign key (从表的外键字段名) references
主表名(主表的主键字段名); #添加外键约束
alter table 表名 drop foreign key 外键名; #删除外键约束
【注意】以上括号、分号均为英文格式下的。
例子
create table category(
cid int not null primary key ,
cname varchar(16)
);
create table book(
bid int ,
bname varchar(50) ,
author char(8) ,
price float,
publisher varchar(50),
discount float,
cid int
);
# 1.给bid字段添加主键约束:
alter table book modify bid int primary key;
# 2.给author字段添加非空约束:
alter table book modify author char(8) not null;
# 3.给banme字段添加唯一约束:
alter table book add unique(bname);
# 4.给publisher字段添加默认约束:
alter table book modify publisher varchar(50) default 'xxx';
# 5.cid字段是category表的外键:
alter table book add constraint fk_cate_book foreign key (cid) references category(cid);
第一次写CSDN,留下学习记录~