foreword
Hi! Happy weekend guys! Presumably you are staying at home on weekends, it is too hot outside! Do what you like to do with the air conditioner at home! In this issue, we mainly study the constraints in MySQL .
Table of contents
1. Add foreign key (when creating)
3. Foreign key constraints (delete/update behavior)Edit
Index overview
1. Concept: Constraints are rules that act on fields in a table to limit the data stored in the table.
2. Purpose: To ensure the correctness, validity and integrity of the data in the database.
3. Classification:
Note: Constraints are applied to the fields in the table, and constraints can be added when creating/modifying tables.
4. According to the classification of the above indexes, a table is given, please create the table according to the appropriate constraints
reference answer
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'用户表';
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, so foreign keys are required.
2. Grammar
1. Add foreign key (when creating)
create 表名(
字段名 数据类型
.......
[constraint] [外键名称] foreign key (外键字段名) reference 主表 (主表列名);
)
( modified to foreign key )
alter table 表名 add constrain 外键名称 foreign key (外键字段名) referencec 主表 (主表列名);
2. Delete the foreign key
alter table 表名 drop foreign key 外键名称;
3. Foreign key constraints (delete/update behavior)
Summarize
This is the end of the learning content of this issue. There are relatively few learning tasks in this issue. I hope that my friends can learn something. See you next time!