1在创建表时后面直接指定约束
2在创建表时最后面直接指定约束
3通过alter增加或删除约束modify
主键和唯一可以用drop ky_id;
唯一约束用key/index
默认约束用set
1.主键约束
单字段主键
create table student (
name varchar(10) primary key;
age tinyint;
);
alter table table1 modify name varchar(10);//取消主键约束;
alter table table1 modify name varchar(10) [constraint key1] primary key;//添加主键约束;
alter table table1 add primary key (name);
create table student (
name varchar(10) prime key;
age tinyint;
[constraint ky_id1] primary key (name);
);
多字段主键
create table student (
name varchar(10) prime key;
age tinyint;
[constraint ky_id1] primary key (name,age);
);
删除、添加主键
alter table table1 add primary key (name);
alter table table1 drop primary key;
2.唯一约束
create table student (
name varchar(10) unique;
age tinyint;
);
alter table table1 modify name varchar(10);//取消唯一约束;
alter table table1 modify name varchar(10) unique;//添加唯一约束;
删除、添加唯一约束
alter table table1 add [constraint ky_id1] unique (name);
alter table table1 drop key/index 唯一约束名;
3.非空约束
create table student (
name varchar(10) not null;
age tinyint;
);
alter table table1 modify name varchar(10);//取消非空约束;
alter table table1 modify name varchar(10) not null;//添加非空约束;
4.默认约束
create table student (
name varchar(10) default '张三';
age tinyint;
);
alter table table1 modify colunm1 set default '张三';//添加
alter table table1 modify colunm1 //取消
alter table table1 modify colunm1 drop default '张三';//取消
;
5.外键约束(on delete cascade)
create table student (
name varchar(10) default '张三';
age tinyint;
[constraint k_id1] foreign key (name) references table2 (colunm1);
);
alter table table1 add [constraint k_id1] foreign key (name) references table2 (colunm1);
alter table table1 drop foreign key 约束名;
自增
aotu_increment=2;//默认增长值为1;可在初始化时设置,modify时修改(增加,取消);
设置自增数值后可修改
alter table table1 auto_increment = 5;