Mysql中约束的操作

117 阅读2分钟

Mysql中约束的操作

1 给指定列添加主键约束

把表名为emp中的列名为id添加主键约束
alter table emp add primary key (id);

image.png

2 Mysql中的自动增长

image.png

把自动增长类型添加到id列的主键上
alter table emp modify id int auto_increment;

image.png

3删除主键

删除emp中id的主键 、此时id中也有自增长类型、应先去掉自增长

去掉自动增长:

alter table emp modify id int;

image.png

删除主键

alter table emp drop primary key;

主键成功删除

image.png

4 添加外键约束

创建表1

departments表包含departments_id,departments_name,location_id;

create table departments(de_id int,de_name varchar(30),lo_id int);

image.png

给de表的de_id列添加主键约束和自动增长

alter table de add primary key(de_id);
alter table de modify de_id int auto_increment;

image.png

给emp表添加dep_id 列

alter table emp add column dep_it int;

添加成功:

image.png

给emp表中的dep_id列中添加外键约束

alter table emp add constraint emp_fk foreign key(dep_id) references de(de_id) 

语句解释:修改epm表 添加名为emp_fk的外键约束 指向de表的de_id列

查看emp表

show create table emp;

image.png

5 删除外键约束

删除名称为emp_fk的外键约束

alter table emp drop foreign key emp_fk;

原有的约束被删除

image.png

6 添加唯一性约束

alter table emp add constraint emp_un unique(name);

修改emp表 给emp-un添加唯一性约束

image.png

7 删除唯一性约束

alter table emp drop key emp_un;

names的唯一性约束被删除

image.png

8 添加非空约束

alter table emp modify pct float(4,2) not null;

emp表的pct列被添加非空约束

image.png

9 删除非空约束

alter table emp modify pct float(4,2) null;

查看emp中的pct列

image.png

10 创建表时添加约束

建表: create table employees(id int,name varchar(10),salary float(8,2));

表名:depts (dept_id ,dept_name,location_id) 1是主键且自动增长,2具有唯一性约束,3有非空约束

create table depts(dept_id int primary key auto_increment,dept_name varchar(30) unique,location_id int not null);

查询表中约束信息:

image.png