Table of contents
I. Overview
- Concept: Constraints are rules that act on fields in a table to limit the data stored in the table.
- Purpose: To ensure the correctness, validity and integrity of the data in the database.
- Classification:
constraint | describe | keywords |
not-null constraint | Restrict the data of this field to not be null | NOT NULL |
unique constraint | Ensure that all data in this field is unique and not repeated | UNIQUE |
primary key constraint | The primary key is the unique identifier of a row of data, which requires non-null and unique | PRIMARY KEY |
default constraint | When saving data, if the value of this field is not specified, the default value will be used | DEFAULT |
check constraints (after version 8.0.16) |
Ensure that the field value satisfies a certain condition | CHECK |
foreign key constraints | It is used to establish a connection between the data of the two tables to ensure the consistency and integrity of the data | FOREIGN KEY |
Note: Constraints are applied to the fields in the table, and constraints can be added when creating/modifying tables.
2. Constraint Demonstration
According to the requirements, complete the creation of the table structure:
field name field meaning Field Type Restrictions constraint keyword id unique ID int Primary key, and auto-increment PRIMARY KEY,AUTO_INCREMENT name Name varchar(10) is not empty and unique NOT NULL,UNIQUE age age int Greater than 0 and less than or equal to 120 CHECK status state char(7) If this value is not specified, it defaults to 1 DEFAULT gender gender char(7) none
create table user(
id int primary key auto_increment comment '主键',
name varchar(10) not null unique comment '姓名',
age int check ( age>= 0 && age <= 120 ) comment '年龄',
status char(1) default '1' comment '状态',
gender char(1) comment '年龄'
)comment '用户表';
-- 添加数据
insert into user(id, name, age, status, gender)
values (1,'Tom',19,'1','男'),(2,'Rose',25,'0','女');
Error judgment:
- Unique constraint (ID is unique):
- Non-null constraint (Name cannot be empty):
- Check constraints (age range):
3. Foreign key constraints
1. Concept
- The foreign key is used to establish a connection between the data of the two tables, so as to ensure the consistency and integrity of the data.
Note: At present, the above two tables have not established foreign key associations at the database level, so the consistency and integrity of the data cannot be guaranteed.
2. Grammar
- Add foreign key:
ALTER TABLE table name ADD CONSTRANT foreign key name FOREIGN KEY (foreign key field name) REFERENCES main table (main table column name);
-- 建表
create table emp(
id int primary key auto_increment comment 'ID',
name varchar(50) not null unique comment '姓名',
age int comment '年龄',
salary int comment '薪资',
entrydate date comment '入职时间',
managerid int comment '直属领导id',
dept_id int comment '部门id'
)comment '员工表';
create table dept(
id int auto_increment comment 'ID' primary key ,
name varchar(50) not null comment '部门名称'
)comment '部门表';
-- 添加数据
insert into dept(id, name)
values (1,'研发部'),(2,'市场部'),(3,'财务部'),(4,'销售部'),(5,'总经办');
insert into emp(id, name, age, salary, entrydate, managerid, dept_id)
values (1,'金庸',66,'总裁',20000,'2000-01-01',null,5),
(2,'张无忌',20,'项目经理',12500,'2005-12-05',1,1),
(3,'杨逍',33,'开发',8400,'2000-11-03',2,1),
(4,'韦一笑',48,'开发',11000,'2002-02-05',2,1),
(5,'常同春',43,'开发',10500,'2004-09-07',3,1);
-- 添加外键
alter table emp add constraint fk_emp_dept_id
foreign key (dept_id) reference dept(id);
- Delete foreign key: ALTER TABLE table name DROP FOREIGN KEY foreign key name;
-- 删除外键
alter table emp drop foreign key fk_emp_dept_id;
3. Delete/Update Behavior
Behavior | illustrate |
NO ACTION | When deleting/updating the corresponding record in the parent table, first check whether the record has a corresponding foreign key, and if so, delete/update is not allowed. (consistent with RESTRICT) |
RESTRICT | When deleting/updating the corresponding record in the parent table, first check whether the record has a corresponding foreign key, and if so, delete/update is not allowed. (consistent with NOACTION) |
CASCADE | When deleting/updating the corresponding record in the parent table, first check whether the record has a corresponding foreign key, and if so, delete/update the record in the child table with the foreign key. |
SET NULL | When deleting the corresponding record in the parent table, first check whether the record has a corresponding foreign key, and if so, set the foreign key value in the child table to null (this requires that the foreign key is allowed to take nul). |
SET DEFAULT | When the parent table is changed, the child table sets the foreign key column to a default value (Innodb does not support) |
Syntax: ALTER TABLE table name ADD CONSTRAINT foreign key name FOREIGN KEY (foreign key field) REERENCES main table name (main table field name) ON UPDATE CASOADE ON DELETE CASCAOE ;
-- 外键的删除和更新行为
-- cascade
alter table emp add constraint fk_emp_dept_id
foreign key (dept_id) references dept(id)
on update cascade on delete cascade ;
-- set null
alter table emp add constraint fk_emp_dept_id
foreign key (dept_id) references dept(id)
on update set null on delete set null ;