修改表实现约束的添加与删除
一、主键约束
添加主键约束
Alter table 表名 add primary key(列名)
例
将 emp 表中的 employee_id 修改为主键且自动增长;
1.添加主键约束;alter table emp add primary key(employee_id);2.添加自增长;alter table emp modify employee_id int auto_increment;
删除主键约束
Alter table 表名 drop primary key
注意:删除主键时,如果主键列具备自动增长能力,需要先去掉自动增长,然后再删除主键;
例
删除 employee_id 的主键约束;
1.去除自动增长;Alter table emp modify employee_id int;2.删除主键约束;Alter table emp drop primary key;
二、非空约束
添加非空约束
Alter table 表名 modify 列名 类型 not null
例
向 emp 表中的 salary 添加非空约束。
Alter table emp modify salary float(8,2) not null;
删除非空约束
Alter table 表名 modify 列名 类型 null
例
删除 salary 的非空约束;
Alter table emp modify salary float(8,2) null;
三、唯一约束
添加唯一约束
Alter table 表名 add constraint 约束名 unique(列名)
例
向 emp 表中的 name 添加唯一约束。
Alter table emp add constraint e_uk unique(name);
删除唯一约束
Alter table 表名 drop key 约束名;
例
删除 name 的唯一约束。
Alter table emp drop key e_uk;
四、外键约束
添加外键约束;
Alter table 表名 add constraint 约束名 foreign key(列名) references 参照表名(参照列名);
例
一、修改 emp 表,添加 dept_id 列。
Alter table emp add column dept_id int;
二、向 emp 表中的 dept_id 列添加外键约束。
Alter table emp add constraint e_fk foreign key(dept_id) references departments(department_id);
删除外键约束;
1.删除外键
Alter table 表名 drop foreign key 约束名;
2.删除外键索引(索引名与约束名相同)
Alter table 表名 drop index 索引名;
例
删除 dept_id 的外键约束;
1.Alter table emp drop foreign key e_fk;2.Alter table emp drop index e_fk;