Overview: 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.1) |
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 graphs to ensure the consistency and integrity of the data |
FOREIGN KEY |
Constraints are applied to the fields in the table, and constraints can be added when creating/modifying tables. Multiple constraints can be added to a field.
foreign key constraints
The foreign key is used to connect the data of the two tables to ensure the consistency and integrity of the data.
Add foreign key:
CREATE TABLE 表名(
字段名 字段类型,
...
[CONSTRAINT] [外键名称] FOREIGN KEY(外键字段名) REFERENCES 主表(主表列名)
);
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名) REFERENCES 主表(主表列名);
-- 例子
alter table emp add constraint fk_emp_dept_id foreign key(dept_id) references dept(id);
Remove foreign keys:
ALTER TABLE 表名 DROP FOREIGN KEY 外键名;
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 NO ACTION) |
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 foreign key record in the child table |
SET NULL |
When deleting/updating 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 (the foreign key is required to allow null) |
SET DEFAULT |
When the parent table is changed, the child table sets the foreign key to a default value (Innodb does not support) |
Change delete/update behavior:
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段) REFERENCES 主表名(主表字段名) ON UPDATE 行为 ON DELETE 行为;