认真学SQL——MySQL入门之表中约束——约束数据的插入和删除

-- 1.主键约束 primary key

特点: 限制主键插入的数据不能为空,不能重复

建表的时候添加主键约束:  create table 表名(主键名 主键类型 primary key , 其他字段...);

注意: 一个表中只能有一个主键

--增
方式一:建表时(推荐使用)
create table stu1(
    id int primary key ,
    name varchar(100),
    age int
);
desc stu1;

方式二:建表后加
create table stu2(
    id int,
    name varchar(100),
    age int
);
alter table stu2 add primary key (id);
desc stu2;

-- 删

方式一:

使用change直接删除主键,非空和唯一约束都没有删除
alter table stu1 change id id VARCHAR(100);

方式二:

使用drop直接删除主键,只是把唯一键删除,不能为空的约束保留
alter table stu2 drop PRIMARY KEY;

再使用change删除非空约束
alter table stu2 change id id VARCHAR(100);

测试:

限制值不能为空,不能重复
insert into stu1(id,name) values (null,'张三'); # 报错Column 'id' cannot be null
insert into stu1(id,name) values (1,'张三'); # 成功
insert into stu1(id,name) values (1,'李四'); # 报错 Duplicate entry '1' for key 'PRIMARY'

-- 2.主键自动增长约束 auto_increment

特点: 默认从1开始,每次自动加1
注意: 如果插入数据的时候指定了id字段,可以使用null或者0占位表示自动使用自增

建表的时候添加主键自增约束:  create table 表名(主键名 主键类型 primary key auto_increment , 其他字段...);

-- 增

方式一:建表时
create table stu3(
    id int primary key auto_increment ,
    name varchar(100),
    age int
);
desc stu3;

方式二:建表后
create table stu4(
    id int primary key,
    name varchar(100),
    age int
);

alter table stu4 change id id int auto_increment;    #如果建表时没加主键可以在auto_increment前加primary key
desc stu4;

-- 删

结论: 如果想要删除主键和自增
1.先用change删除自增

alter table stu3 change id id int ;

2.再用drop删除主键中的唯一约束

alter table stu3 drop PRIMARY KEY ;

3.最后用change删除非空约束

alter table stu3 change id id int ;

-- 3.非空约束 not null

特点: 限制对应数据不能为空null

建表的时候添加非空约束:  create table 表名(主键名 主键类型 primary key ,字段名 字段类型 not null , 其他字段...);

注意: 一个表中可以有多个非空约束

-- 增

创建表
create table stu4(
    id int not null,
    name varchar(100) not null,
    age int
);

查看表结构
desc stu4;

添加非空约束
alter table stu4 change age age int not null;

-- 删

删除非空约束
alter table stu4 change age age int;

--4.唯一约束 unique

特点: 限制对应的数据不能重复

建表的时候添加唯一约束:  create table 表名(主键名 主键类型 primary key ,字段名 字段类型 unique, 其他字段...);

注意: 一个表中可以有多个唯一约束

创建表时设置
create table stu5(
    id int not null unique ,
    name varchar(100) unique ,
    age int
);

查看表结构
desc stu5;

-- 增

添加唯一约束(自动添加唯一索引,索引名就是字段名)
alter table stu5 change age age int unique ;

添加唯一索引(手动添加唯一索引,自定义索引名称)
create unique index age_index on stu5 (age);

-- 删

删除唯一约束(本质就是删除唯一索引)
drop index age on stu5;

删除唯一约束(本质就是删除唯一索引)
drop index age_index on stu5;

-- 5.默认约束 default

特点: 可以提前给字段设置默认值

建表的时候添加默认约束:  create table 表名(主键名 主键类型 primary key ,字段名 字段类型 default 默认值, 其他字段...);

注意: 一个表中可以有多个默认约束

-- 增

创建表时设置
create table stu6(
    id int primary key auto_increment,
    name varchar(100) default 'admin',
    pwd varchar(100) default '123456'
);

添加默认约束
alter table stu7 change name name varchar(100) default 'admin';
alter table stu7 change pwd pwd varchar(100) default '123456';

-- 删

删除默认约束
alter table stu7 change name name varchar(100);
alter table stu7 change pwd pwd varchar(100);

你可能感兴趣的:(sql,mysql,数据库)