当前位置:网站首页>MySQL foundation - constraints
MySQL foundation - constraints
2022-06-22 20:23:00 【White chocolate x】
Catalog
In the last article, we learned MySQL Basics —— function , This article is for us to learn MySQL Basics —— constraint .
constraint
Constraints are rules that act on fields in a table , Used to limit the data stored in a table , Its purpose is to ensure that the data in the database is correct 、 Effectiveness and integrity .
Common constraints are as follows :
| constraint | describe | keyword |
|---|---|---|
| Non empty constraint | Limit the data of this field to null | NOT NULL |
| Unique constraint | Ensure that all data in this field is unique 、 Not repeated | UNIQUE |
| Primary key constraint | A primary key is the unique identifier of a row of data , It is required to be non empty and unique | PRIMAPY KEY |
| Default constraint | When saving data , When the value of this field is not specified , The default value is used | DEFAULT |
| Detection constraints (8.0 After the version ) | Ensure that the field value meets a certain condition | CHECK |
| Foreign key constraints | Make a connection between the data of two tables , Ensure data consistency and integrity | FOREIGN KEY |
Be careful : Constraints act on fields in a table , You can create a table / Add constraints when modifying tables .
Case study
Next, we use a case to demonstrate how to set constraints when creating a data table .
Case requirements are as follows :
| Field name | Field meaning | Field type | constraint condition | Constraint keywords |
|---|---|---|---|---|
| id | ID Unique identification | int | Primary key , And grow automatically | PRIMARY KEY,AUTO_INCREMENT |
| name | full name | varchar(10) | Not empty and unique | NOT NULL,UNIQUE |
| passwrod | password | varchar(10) | The default value is 123456 | DEFAULT |
| gender | Gender | char(1) | nothing |
The sample code is as follows :
CREATE TABLE students(
id int PRIMARY KEY AUTO_INCREMENT COMMENT ' user id',
name varchar(10) NOT NULL UNIQUE COMMENT ' full name ',
password varchar(10) DEFAULT '123456' COMMENT ' password ',
gender char(1) COMMENT ' Gender '
)COMMENT ' Student list ';As shown in the figure below :

This will successfully create constraints for fields when creating tables .
Foreign key constraints
Foreign keys are used to connect the data of two tables , So as to ensure the consistency and integrity of data .
Add foreign keys
Add foreign key syntax format as follows :
# Add foreign keys when creating tables
CREATE TABLE Table name (
Field name data type ,
...
[CONSTRAINT] [ Foreign key name ] FOREIGN KEY ( Foreign key field name ) REFERENCES Main table ( Name of main table )
);
# Add a foreign key after creating a table
ALTER TABLE Table name ADD CONSTRAINT Foreign key name FOREIGN KEY ( Foreign key field name ) REFERENCES Main table ( Name of main table );The sample code is as follows :
# Word list
CREATE TABLE classinfo(
id int PRIMARY KEY AUTO_INCREMENT COMMENT ' class id',
name varchar(50) NOT NULL COMMENT ' Class name '
)COMMENT ' Class table ';
# Main table
CREATE TABLE students(
id int PRIMARY KEY AUTO_INCREMENT COMMENT 'id',
name varchar(50) NOT NULL COMMENT ' Student name ',
password varchar(10) DEFAULT '123456' COMMENT ' password ',
gender char(1) COMMENT ' Gender ',
classid int NOT NULL COMMENT ' class id',
CONSTRAINT fk_students_classinfo_id FOREIGN KEY (classid) REFERENCES classinfo(id)
)COMMENT ' Class table ';As shown in the figure below :


Delete foreign key
The syntax format for deleting foreign keys is as follows :
ALTER TABLE Table name DROP FOREIGN KEY Foreign key name ;The sample code is as follows :
ALTER TABLE students DROP FOREIGN KEY fk_students_classinfo_id;As shown in the figure below :

Next, we add foreign keys in another way , The code is as follows :
ALTER TABLE students ADD CONSTRAINT fk_student_classinfo FOREIGN KEY (classid) REFERENCES classinfo(id);As shown in the figure below :

Behavior
After setting the foreign key , You can't easily delete the data in the data table , This is because there is a foreign key constraint behavior —— Delete / Update behavior .
Foreign key deletion / Update behaviors are :
| Behavior | explain |
|---|---|
| NO ACTION | When deleting in the parent table / When updating the corresponding record , First, check whether the record has a corresponding foreign key , If there is, it is not allowed to delete / to update . |
| RESTRICT | When deleting in the parent table / When updating the corresponding record , First, check whether the record has a corresponding foreign key , If there is, it is not allowed to delete / to update . |
| CASCADE | When deleting in the parent table / When updating the corresponding record , First, check whether the record has a corresponding foreign key , If there is , Then delete / Update the record of the foreign key in the sub table . |
| SET NULL | When deleting the corresponding record in the parent table , First, check whether the record has a corresponding foreign key , If yes, set the foreign key value in the sub table to null( Foreign keys are required and allowed to be null) |
| SET DEFAULT | When the parent table changes , The sub table sets the foreign key column to a default value (Innodb I won't support it ) |
Set delete for foreign keys / The update behavior syntax format is as follows :
ALTER TABLE Table name ADD CONSTRAINT Foreign key name FOREIGN KEY ( Foreign key field ) REFERENCES Main table name ( Main table fields ) ON UPDATE Behavior ON DELETE Behavior ;The sample code is as follows :
ALTER TABLE students ADD CONSTRAINT fk_student_classinfo FOREIGN KEY (classid) REFERENCES classinfo(id) ON UPDATE CASCADE ON DELETE CASCADE;As shown in the figure below :

Be careful : Delete / The update behavior should be consistent .
Okay ,MySQL Basics —— That's where constraints come in , Next article study MySQL Basics —— Multi-table query .
边栏推荐
- 树莓派环境设置
- Summary of 2019: 31 is just another start
- A text to show you the memory leak
- 【Proteus仿真】74LS138译码器流水灯
- EasyDSS问题及解决方案汇总
- Metu stability and operation and maintenance guarantee scheme
- Comment le sac à dos complet considère - t - il la disposition?
- I wrote a telnet command myself
- Async-profiler介绍
- Redis持久化的几种方式——深入解析RDB
猜你喜欢
![[deeply understand tcapulusdb knowledge base] common problems in deploying tcapulusdb local](/img/2b/3ab5e247ac103728b4d3579c3c5468.png)
[deeply understand tcapulusdb knowledge base] common problems in deploying tcapulusdb local

三维天地助力实验室夯实完整质量体系管理
![[in depth understanding of tcapulusdb technology] getting started with MySQL driver](/img/7b/8c4f1549054ee8c0184495d9e8e378.png)
[in depth understanding of tcapulusdb technology] getting started with MySQL driver

client-go gin的简单整合十一-Delete

ROS从入门到精通(八) 常用传感器与消息数据

MySQL基础——函数

How should programmers look up dates

一张图解码 OpenCloudOS 社区开放日

市场开始降温,对NFT 是坏事么?

程序员应该怎么查日期
随机推荐
支持在 Kubernetes 运行,添加多种连接器,SeaTunnel 2.1.2 版本正式发布!
漫话Redis源码之一百二十二
一个支持IPFS的电子邮件——SKIFF
[deeply understand tcapulusdb technology] view the online operation of tcapulusdb
Oh, my God, it's a counter attack by eight part essay
Recv function with timeout
[petty bourgeoisie database] break down the concept: data, database, database system, database management system, database technology
Heap sort (principle plus code)
[deeply understand tcapulusdb technology] tcapulusdb table management - rebuild table
MySQL Basics - functions
Dynamicdatabasesource, which supports the master-slave database on the application side
[graduation season] step by step? Thinking about four years of University by an automation er
JWT简介
What can the accelerated implementation of digital economy bring to SMEs?
Latest download address of libcef - compiled as MD dynamic link under vs2015
Introduction of Neural Network (BP) in Intelligent Computing
Merge sort (recursive and iterative Implementation)
socket的connect函数用法
[deeply understand tcapulusdb technology] tcapulusdb process
51万奖池邀你参战!第二届阿里云ECS CloudBuild开发者大赛来袭