约束
约束的作用:为了保证数据的有效性和完整性
mysql中常用的约束:
主键约束(primary key)
自增长约束(auto_incrment)加在整数型的字段配合主键约束来使用
唯一约束(unique)
非空约束(not null)
外键约束(foreign key)
枚举类型 sex ENUM(‘男’,‘女’)
非负约束 UNSIGNED
例如:TINYINT 也能表示的范围 -128------127
添加了这个约束 TINYINT UNSIGNED
主键约束:被修饰过的字段唯一非空
注意:一张表只能有一个主键,这个主键可以包含多个字段
主键的创建方式
方式一:建表的同时添加约束 格式:字段名 字段类型 primary key
方式二:建表的同时在约束区域添加约束
所有的字段声明完成之后,就是约束区域了
格式: primary key(字段1,字段2)
正确:
create table pk01(
id int,
username varchar(20),
primary key (id)
);
添加值
insert into pk01 values(1,'tom');-- 成功
insert into pk01 values(1,'tom');-- 失败 Duplicate entry '1' for key 'PRIMARY'
insert into pk01 values(null,'tom');-- 失败 Column 'id' cannot be null
错误:
create table pk01(
id int primary key,
username varchar(20),
primary key (id)
);-- 错误的 一张表只能有一个主键
方式三:建表之后通过修改表结构添加约束
建表之后
create table pk02(
id int,
username varchar(20)
);
添加主键
alter table pk02 add primary key(字段名1,字段名2..);
alter table pk02 add primary key(id,username);
添加值
insert into pk02 values(1,'tom');-- 成功
insert into pk02 values(1,'tomcat');-- 成功
insert into pk02 values(1,'tomcat');-- 失败
删除主键约束:分两种情况
- 情况1:这个字段只有主键约束,分两步来删除主键约束
第一步:删除主键的唯一性
alter table 表名 drop primary key;这样只删除了唯一性,还要删除非空性
第二步:删除主键非空
alter table (表名) modify (列名) varcahr(20) null;修改了字段名还为原来的字段加上null即可 - 情况2:这个字段是一个int类型的字段,既有主键约束又有自增长约束,得先删除自增长约束,再删除主键约束
第一步:删除自增长约束,修改自增长字段名和数据类型还为原来的字段名和数据类型
select table 表名 change 原字段名 现字段名 现数据类型;
第二步:删除主键约束
selete table 表名 drop primary key
第三步:删除非空约束
ALTER TABLE test3 MODIFY sid INT NULL;–修改字段值为null就可以了
唯一约束(了解)
- 概念:被修饰过的字段唯一,对null不起作用
- 方式一:建表的时候添加约束 格式:字段名 字段类型 unique
create table un(
id int unique,
username varchar(20) unique
);
insert into un value(10,'tom');-- 成功
insert into un value(10,'jack');-- 错误 Duplicate entry '10' for key 'id'
insert into un value(null,'jack');-- 成功
insert into un value(null,'rose');-- 成功
- 方式二:建表的时候在约束区添加条件
所有的字段声明完成之后就是约束区域了
unique(字段1,字段值); - 方式三:建表之后,通过修改表结构添加约束
alter table 表名 add unique(字段1,字段2);添加的联合唯一
alter table 表名 add unique (字段1)给一个添加唯一
alter table 表名 add unique (字段2)给另一个添加唯一
create table un01(
id int,
username varchar(20)
);
alter table un01 add unique(id,username);
insert into un01 values(1,'tom');-- 成功
insert into un01 values(1,'jack');-- 成功
insert into un01 values(1,'tom');-- 失败 Duplicate entry '1-tom' for key 'id'
非空约束(了解)
- 特点: 被修饰过的字段非空
- 方式:
create table nn(
id int not null,
username varchar(20) not null
);
insert into nn values(null,'tom');-- 错误的 Column 'id' cannot be null
truncate清空表
- 格式:truncate 表名;干掉表,重新创建一张空表
- 和delete form 区别:
delete属于DML语句 truncate 属于DDL语句
deelte逐条删除,truncate 干掉表,重新创建一张空表
auto_increment 自增
- 要求:
1.被修饰的字段类型支持自增,一般是int
2.被修饰的字段必须是一个key 一般是 primary key
create table ai01(
id varchar(10) auto_increment
);-- 错误 Incorrect column specifier for column 'id'
create table ai01(
id int auto_increment
);-- 错误 Incorrect table definition; there can be only one auto column and it must be defined as a key