MySQL-约束
一、约束:
作用:
为了保证数据的有效性和完整性
mysql中常用的约束:
主键约束(primary key) 唯一约束(unique) 非空约束(not null) 外键约束(foreign key)
二、主键约束:
被修饰过的字段唯一非空
注意:一张表只能有一个主键,这个主键可以包含多个字段
方式1: 建表的同时增加约束 格式: 字段名称 字段类型 primary key
方式2: 建表的同时在约束区域增加约束
所有的字段声明完后之后,就是约束区域了
格式:primary key(字段1,字段2)
例如:
create table one(
id int,
usename varchar(20),
primary key (id)
);
--错误的方式(一张表只能有一个主键):
create table one(
id int primary key,
username varchar(20),
primary key (id)
);
方式三:建表之后,通过修改表结构增肌约束
alter table one add primary key(字段名1,字段名2...);
alter table one add primary key(id,username); --联合主键
insert into one values(1,'zhangsan'); --成功
insert into one values(1,'lisi'); --成功
insert into one values(1,'lisi'); --失败
方式一:只能创建一个主键,方式二方式三可以创建多个主键。
三、唯一约束:
被修饰过的字段唯一,对null不起作用
方式一:建表的同事增加约束 格式:字段名称 字段类型 unique
例如 :
create table two(
id int unique,
username varchar(20) unique
);
insert into two value(1,'张三'); --成功
insert into two value(1,'李四'); --错误
insert into two value(null,'张三'); --成功
insert into two value(null,'张三'); --成功
方式二:建表的同时在约束区域增加约束
所有的字段声明完成之后,就是约束区域了
unique(字段1,字段值2...)
方式三: 建表之后,通过修改表结构增加约束
alter table 表名 add unique (字段1,字段2);--增加联合唯一
alter table 表名 add unique (字段1);--给一个
alter table 表名 add unique (字段2);--给另一个
四、非空约束
特点:被修饰过的字段非空
方式:
create table three(
id int not null,
username varchar(20) not null
);
insert into three values(null,'张三'); --错误的
备注:由于个人原因,本博客暂停更新。如有问题可联系本人,本人提供技术指导、学习方向、学习路线。本人微信wlp1156107728(添加注明来意) QQ1156107728(添加注明来意)