mysql数据库约束
常见约束
分类:六大约束
| 名称 | 含义 |
|---|---|
| not null | 非空,用于保证该字段的值不能为空 |
| default | 默认,用于保证该字段有默认值 |
| primary key | 主键,用于保证该字段的值具有唯一性,并且非空 |
| unique | 唯一,用于保证该字段的值具有唯一性,可以为空 |
| check | 检查约束(mysql中不支持) |
| foreign key | 外键,用于限制两个表的关系,用于保证该字段的值必须来自于主表的关联列的值 |
添加约束的时机:
- 1.创建表
- 2.修改表
约束的添加分类:
- 1.列级约束
- 2.表级约束
创建表时添加列级约束
create table stuinfo(
id int primary key ,
stuName varchar(20) not null ,
gender char(1) check ( gender='男'or gender='女'),
seat int unique ,
age int default 18,
magorId int references magor(id)
);
create table magor(
id int primary key ,
magorName varchar(20)
);
-- 查看索引
show index from stuinfo;
创建表时添加表级约束
drop table if exists stuinfo;
create table stuinfo(
id int ,
stuName varchar(20) ,
gender char(1) ,
seat int ,
age int ,
magorId int,
constraint pk primary key (id),
constraint uq unique (seat),
constraint ck check ( gender='男'or gender='女' ),
constraint fk_stuinfo_major foreign key (magorId) references magor(id)
);
drop table if exists magor;
create table magor(
id int primary key ,
magorName varchar(20)
);
或者
-- 删除表
drop table if exists stuinfo;
drop table if exists magor;
-- 创建表
create table stuinfo
(
id int,
stuName varchar(20),
gender char(1),
seat int,
age int,
magorId int,
primary key (id),
unique (seat),
check ( gender = '男' or gender = '女' ),
foreign key (magorId) references magor (id)
);
create table magor
(
id int primary key,
magorName varchar(20)
);
primary key 和unique
主键和唯一的对比
| 名称 | 保证唯一性 | 是否允许为空 | 一个表中可以有多少个 | 是否允许组合 |
|---|---|---|---|---|
| primary key | 是 | 否 | 最多有一个 | 允许,但是不推荐 |
| unique | 是 | 是 | 可以有多个 | 允许,但是不推荐 |
外键
特点:
- 1.要求在从表设置外键关系
- 2.从表的外键列的类型和主表的关联列的类型要求一致或者兼容,名称无要求。
- 3.主表的关联列必须时一个key(一般是主键或者唯一)
- 4.插入数据时,先插入主表,再插入主表
- 5.删除数据时,先删除从表,再删除主表。
修改表时添加约束
-- 删除表
drop table if exists stuinfo;
drop table if exists magor;
-- 创建表
create table stuinfo
(
id int,
stuName varchar(20),
gender char(1),
seat int,
age int,
magorId int
#
# primary key (id),
# unique (seat),
# check ( gender = '男' or gender = '女' ),
# foreign key (magorId) references magor (id)
);
-- 添加非空约束
alter table stuinfo modify column stuName varchar(20) not null;
-- 添加默认约束
alter table stuinfo modify column age int default 18;
-- 添加主键 ,列级约束
alter table stuinfo modify column id int primary key ;
-- 添加主键 ,表级约束
alter table stuinfo add primary key (id);
-- 添加唯一 ,列级约束
alter table stuinfo modify column seat int unique;
-- 添加唯一 ,表级约束
alter table stuinfo add unique (seat);
-- 添加外键 ,列级约束
alter table stuinfo add constraint fk_stuinfo_magor foreign key (magorId) references magor(id);
-- 修改表时,删除元素
alter table stuinfo modify column stuName varchar(20) null;
alter table stuinfo modify age int;
alter table stuinfo drop primary key;
create table magor
(
id int primary key,
magorName varchar(20)
);
本文来自博客园,作者:King-DA,转载请注明原文链接:https://www.cnblogs.com/qingmuchuanqi48/articles/15970096.html

浙公网安备 33010602011771号