Home  >  Article  >  Database  >  Example analysis MySQL constraint knowledge points

Example analysis MySQL constraint knowledge points

WBOY
WBOYforward
2022-07-14 17:12:302403browse

This article brings you relevant knowledge about mysql, which mainly sorts out issues related to constraints. Constraints are to ensure the integrity of the data. Data integrity refers to the accuracy and accuracy of the data. Reliability is proposed to prevent the existence of data that does not comply with semantic regulations in the database and to prevent invalid operations or error messages caused by the input and output of incorrect information. Let's take a look at it together. I hope it will be helpful to everyone.

Example analysis MySQL constraint knowledge points

Recommended learning: mysql video tutorial

1. Overview of constraints

1.1 Why constraints are needed -- In order to ensure the integrity of data

Data integrity (Data Integrity) refers to the accuracy (Accuracy) and reliability (Reliability) of the data. It is proposed to prevent the existence of data that does not comply with semantic regulations in the database and to prevent invalid operations or error messages caused by the input and output of incorrect information.

In order to ensure the integrity of the data, SQL Norms restrict the Table data carries out additional conditional restrictions . Consider the following four aspects:

Entity Integrity ) : For example, there cannot be two identical and indistinguishable records in the same table

Domain Integrity (Domain Integrity ) : For example: age range 0-120 , gender range " male / female ”

                         Referential Integrity ) : For example: the department where the employee is located, this department must be found in the department table

User-defined integrity (User - defined Integrity ) : For example: the user name is unique, the password cannot be empty, etc. The salary of the manager of this department must not be higher than 5% of the average salary of the employees in this department. times.

1.2 What are constraints - restrictions on fields in the table

Constraints are mandatory regulations at the table level.

allowable Specify constraints when creating a table (via CREATE TABLE ​ statement) , or in Passed after table creation ALTER TABLE Statement stipulation

Constraints .

1.3 Classification of constraints

According to the restrictions of the constraint data columns, Constraints can be divided into:

Single column constraint : Each constraint only constrains one column

Multi-column constraints : Each constraint can constrain multiple columns of data

According to the scope of the constraint , constraints can be divided into:

Column level constraints : Can only be applied to one column, following the definition of the column

Table-level constraints : Can be applied to multiple columns, not together with columns, but defined separately


##Position

Supported constraint types

Is it possible to name the constraint

##Column level constraints:

The syntax behind the

column is supported, but foreign keys have no effect.

Can't

Table-level constraints:

Below all columns

Default and non-empty are not supported, others are supported

Yes (primary key has no effect )

According to the role of constraints , constraints can be divided into:

1. NOT NULL non-null constraint, which stipulates that a certain field cannot be empty

2. UNIQUE unique constraint, which stipulates that a certain field is unique in the entire table

3. PRIMARY KEY primary key (non-null and unique) constraint

4. FOREIGN KEY foreign key constraints

5. CHECK check constraints

6. DEFAULT default value constraint

Note: MySQL does not support check constraints, but you can use checkConstraints without any effect

View existing constraints of a table:

       # information_schema database name (system library)

           # table_constraints table name (specially stores the constraints of each table)

## SELECT * FROM information_schema.table_constraints

WHERE table_name = 'Table name';

2. Non-null constraint (NOT NULL)

2.1 Function

                                                                                                                                       ## The value of a certain column is not allowed to be empty

2.2 Keywords

           NOT NULL

2.3 Features

        1. Default, All types of values ​​can be NULL

, including INT, FLOAT and other data types ## 2. Non-null constraints can only appear on columns of table objects. Only a certain column can be qualified as non-null independently, and non-null cannot be combined.

                                                          (only column-level constraints, no table-level constraints)

3. A table can have many columns that are respectively restricted to be non-null

4. The empty string ''

is not equal to NULL, 0 is not equal to NULL 2.4 Add a non-null constraint2.4.1 Add a non-null constraint when CREATE TABLE

Grammar format:

        CREATE TABLE 
   表名称( 
  
                字段名 数据类型, 
  
                字段名 数据类型 NOT NULL, 
  
                字段名 数据类型 NOT NULL 
  
        );

Example:

##2.4.2 Add non-null constraints in ALTER TABLE

Syntax format:

        
alter table 
表名称 
modify 
字段名 数据类型 
not 
null
;

Example:

2.5 删除非空约束

语法格式:     

        1.alter table 
   表名称 modify 字段名 数据类型 NULL; #去掉not null,相当于修改某个非注解字段,该字段允 许为空 
  
        2.alter table 表名称 modify 字段名 数据类型; #去掉not null,相当于修改某个非注解字段,该字段允许为空

举例:

3. 唯一性约束(UNIQUE 或 UNIQUE KEY)

3.1 作用

        用来限制某个字段/   某列的值不能重复。  

3.2 关键字

        UNIQUE

3.3 特点

        1.同一个表可以有多个唯一约束。

        2.唯一约束可以是某一个列的值唯一,也可以多个列组合的值唯一。

        3.唯一性约束允许列值为空。并且允许存在多个NULL值。

        4.在创建唯一约束的时候,如果不给唯一约束命名,就默认和列名相同。

        5.MySQL会给唯一约束的列上默认创建一个唯一索引。

3.4 添加唯一约束

3.4.1 在CREATE TABLE 时添加唯一约束

语法格式:

        1.列级约束

        create table 
   表名称( 
  
        字段名 数据类型, 
  
        字段名 数据类型 unique, 
  
        字段名 数据类型 unique key, 
  
        字段名 数据类型 
  
        );

          2.表级约束  

        create table 
   表名称( 
  
        字段名 数据类型, 
  
        字段名 数据类型, 
  
        字段名 数据类型, 
  
        [constraint 约束名] unique key(字段名) 
  
        );

举例:

 

3.4.2 在ALTER TABLE 时添加唯一约束

语法格式:

          1. alter table 表名称
            add  [constraint 约束名] unique key(字段列表);
        2. alter table 表名称
            modify 字段名 字段类型 unique;

注:字段列表中如果是一个字段,表示该列的值唯一。如果是两个或更多个字段,那么复合唯一,即多个字段的组合是唯一的   

举例:  

3.4.3 添加复合唯一性约束

语法格式:

        1.在  create table 时添加复合唯一约束

                create table 表名称( 
  
                字段名 数据类型, 
  
                字段名 数据类型, 
  
                字段名 数据类型, 
  
                 [constraint 约束名] unique key(字段列表) 
  
                );

        2.  在 alter table 时添加复合唯一约束   

                alter table 表名称 
    
                add  [constraint 约束名] unique key(字段列表);

        字段列表中写的是多个字段名,多个字段名用逗号分隔,表示那么是复合唯一,即多    

个字段的组合是唯一的     

举例:  

 

 

3.5 删除唯一约束

        1.添加唯一性约束的列上也会自动创建唯一索引。  

        2.删除唯一约束只能通过删除唯一索引的方式删除。  

        3.删除时需要指定唯一索引名,唯一索引名就和唯一约束名一样。  

        4.如果创建唯一约束时未指定名称,如果是单列,就默认和列名相同;  

           如果是组合列,那么默认和() 中排在第一个的列名相同。  

           也可以是自定义唯一性约束名。    

语法格式:

        ALTER TABLE USER 
  
        DROP INDEX 约束名;

查看表从索引:    

        show index from 表名称
     ;

举例:  

4. PRIMARY KEY 约束(主键约束)

4.1 作用

        用来唯一标识表中的一行记录。    

4.2 关键字

        primary key    

4.3 特点

        主键约束相当于唯一约束+非空约束的组合,主键约束列不允许重复,也不允许出现空值。  

        1. 一个表最多只能有一个主键约束,建立主键约束可以在列级别创建,也可以在表级别上创建。  

        2. 主键约束对应着表中的一列或者多列(复合主键)  

        3. 如果是多列组合的复合主键约束,那么这些列都不允许为空值,并且组合的值不允许重复。  

        4. MySQL的主键名总是    PRIMARY    ,就算自己命名了主键约束名也没用。  

        5. 当创建主键约束时,系统默认会在所在的列或列组合上建立对应的    主键索引    (能够根据主键查询的,就根据主键查询,效率更高)。如果删除主键约束了,主键约束对应的索引就自动删除了。  

        6. 需要注意的一点是,不要修改主键字段的值。因为主键是数据记录的唯一标识,如果修改了主键的值,就有可能会破坏数据的完整性   

4.4 添加主键约束

4.4.1 在CREATE TABLE 时添加主键约束

语法格式:   

           1.列级模式  

                create table 表名称( 
  
                字段名 数据类型 primary key, #列级模式 
  
                字段名 数据类型, 
  
                字段名 数据类型 
  
                );

        2.表级模式(注:    MySQL的主键名总是    PRIMARY    ,就算自定义了主键约束名也没用    )  

                create table 表名称( 
  
                字段名 数据类型, 
  
                字段名 数据类型, 
  
                字段名 数据类型, 
  
                [constraint 约束名] primary key(字段名) #表级模式 
  
                );

举例:  

4.4.2 在CREATE TABLE 时添加复合主键约束

        多列组合的复合主键约束,那么这些列都不允许为空值,并且组合的值不允许重复。

语法格式:

        create table 
    表名称( 
  
        字段名 数据类型, 
  
        字段名 数据类型, 
  
        字段名 数据类型, 
  
        primary key(字段名1,字段名2) 
  
        );

字段1和字段2的组合是唯一的,也可以有更多个字段   

举例:   

4.4.3  在 ALTER TABLE 时添加(复合)主键约束

        字段列表可以是一个字段,也可以是多个字段,如果是多个字段的话,是复合主键     

语法格式:

        1. ALTER TABLE 表名称 MODIFY 字段名 数据类型 PRIMARY KEY;
        2. ALTER TABLE 表名称 ADD PRIMARY KEY(字段列表);

举例:  

4.5 删除主键约束 

        删除主键约束,不需要指定主键名,因为一个表只有一个主键,     删除主键约束后,非空还存在。     (但在实际开发中,不会去删除表中的主键约束)     

语法格式:  

        
    alter table 表名称 
  
        drop primary key;

举例:  

5. 自增列:AUTO_INCREMENT

5.1 作用

        某个字段的值自增      

5.2 关键字

        auto_increment      

5.3 特点和要求

            1. 一个表最多只能有一个自增长列    

        2. 当需要产生唯一标识符或顺序值时,可设置自增长    

        3. 自增长列约束的列必须是键列(主键列,唯一键列)    

        4. 自增约束的列的数据类型必须是整数类型    

        5. 如果自增列指定了 0 和 null,会在当前最大值的基础上自增;如果自增列手动指定了具体值,直接 赋值为具体值     

5.4 添加自增约束

5.4.1 在CREATE TABLE 时添加自增约束

语法格式:

                create table 
    表名称( 
  
                字段名 数据类型 primary key auto_increment,
  
                字段名 数据类型 ,
  
                字段名 数据类型 ,
  
                字段名 数据类型 
  
                );
  
                create table 表名称( 
  
                字段名 数据类型 ,
  
                字段名 数据类型 unique key auto_increment, 
  
                字段名 数据类型 
  
                );

举例:  

非法创建:

 正确创建方式:

插入数据: 

 特殊情况(不推荐此写法):

5.4.2 在 ALTER TABLE 时添加自增约束

语法格式:   

        alter table 
    表名称 
  
        modify 字段名 数据类型 auto_increment;

举例:  

5.5 删除自增约束

语法格式:   

        alter table 表名称 modify 字段名 数据类型;

举例:  

5.6 MySQL 8.0新特性—自增变量的持久化

        在MySQL 8.0    之前,自增主键    AUTO_INCREMENT    的值如果大于    max(primary key)+1    ,在    MySQL    重启后,会重 置AUTO_INCREMENT=max(primary key)+1    ,这种现象在某些情况下会导致业务主键冲突或者其他难以发 现的问题。 下面通过案例来对比不同的版本中自增变量是否持久化。   

案例:  

        对于MySQL5.7版本: 

 然后重启MySQL57服务器:(以管理员的身份运行)

 

It can be seen from the results that the newly inserted 0 The value assigned is 4 , according to the operation logic before restart, it should be allocated here 6 . The main reason for the above results is that the auto-incrementing primary key is not persisted.

In the MySQL 5.7 system, the allocation rules for auto-incrementing primary keys are determined by InnoDB One inside the data dictionary Counter to decide, and the counter is only in In-memory maintenance , will not be persisted to disk. This counter will be initialized when the database is restarted.

For MySQL8.0 version:

Then restart the MySQL80 server: (Run as administrator)

It can be seen from the results that the auto-increment variable has been persisted.

MySQL 8.0 persists the counter of the auto-incrementing primary key to Redo log middle. Every time a counter changes, it is written to the redo log. If the database is restarted, InnoDB The memory value of the counter will be initialized based on the information in the redo log.

6. FOREIGN KEY constraint

6.1 Function

Limit the referential integrity of a field in a table.

For example, the choice of employees' employees must find the corresponding part in the department table.

##6.2 Keywords

FOREIGN KEY

6.3 Master table and slave table/parent table and child table

Master Table (parent table): referenced table, referenced table

                                                                                                                                                         out out outps out outps out out out out’’ so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so to so so so so so so so so so so so so to so to so so so so so so to to to to to to to to to to to to to to to to to to to’’’’s withhold with basis with account with respect to, [delivery with], , the employee table is the slave table.

For example: student schedule, course schedule, course selection schedule: students and courses in the course selection schedule should refer to the student schedule and course schedule respectively. The student schedule and course schedule are the master schedules, and the course selection schedule is the slave schedule.​

6.4 Features

1. From the foreign key column of the table, Must reference/reference the primary key or unique constraint column of the main table

            因为被依赖/被参考的值必须是唯一的     

        2. 在创建外键约束时,如果不给外键约束命名,默认名不是列名,而是自动Generate a foreign key name (for example, student_ibfk_1;), and you can also specify a foreign key constraint name.

3. If you specify foreign key constraints when creating (CREATE) a table, create the master table first, and then create the slave table

4. When deleting a table, delete the slave table first (or delete it first Foreign key constraints), and then delete the main table. The data in the main table can then be deleted

6. Specify foreign key constraints in the "slave table", and a table can establish multiple foreign key constraints

        7. 从表的外键列与主表被参照的列名字可以不相同,但是数据类型必须一样,逻辑意义一致。如果类型不一样,创建子表时,就会出现错误。     

        8.      当创建外键约束时,系统默认会在所在的列上建立对应的普通索引。但是索引名是外键的约束名。(根据外键查询效率很高)      

        9. 删除外键约束后,必须 手动 删除对应的索引     

6.5 添加外键约束

6.5.1 在 create table 时添加外键约束

语法格式:

     
         create table 
     主表名称( 
    
        字段1 数据类型 primary key, 
    
        字段2 数据类型 
    
        );
    
        create table 从表名称( 
    
        字段1 数据类型 primary key, 
    
        字段2 数据类型, 
    
        [CONSTRAINT <外键约束名称>] FOREIGN KEY(从表的某个字段) references 主表名(被参考字段) [on update xx][on delete xx];
    
        );

-- FOREIGN KEY: 在表级指定子表中的列      

-- REFERENCES: 标示在父表中的列       

(从表的某个字段)的数据类型必须与主表名(被参考字段)的数据类型一致,逻辑意义也一样    

(从表的某个字段)的字段名可以与主表名(被参考字段)的字段名一样,也可以不一样       

举例:  

正确的创建方式:

 错误的创建方式:

 添加数据:

 修改数据:

 删除数据:

 6.5.2 在ALTER TABLE 时添加外键约束

        一般情况下,表与表的关联都是提前设计好了的,因此,会在创建表的时候就把外键约束定义好。不过,如果需要修改表的设计(比如添加新的字段,增加新的关联关系),但没有预先定义外键约束,那么,就要用修改表的方式来补充定义。    

语法格式:   

        ALTER TABLE 从表名 
    
        ADD [CONSTRAINT 约束名] FOREIGN KEY (从表的字段) REFERENCES 主表名(被引用 字段) [on update xx][on delete xx];

6.7 约束等级(级联)

       1.  Cascade    方式    :在父表上    update/delete    记录时,同步    update/delete    掉子表的匹配记录  

        2. Set null方式    :在父表上    update/delete    记录时,将子表上匹配记录的列设为    null    ,但是要注意子 表的外键列不能为not null  

        3. No action方式    :如果子表中有匹配的记录,则不允许对父表对应候选键进行    update/delete    操作  

        4 .Restrict方式 (默认)    :同no action    , 都是立即检查外键约束  

        5. Set default方式    (在可视化工具    SQLyog    中可能显示空白):父表有变更时,子表将外键列设置成一个默认的值,但Innodb    不能识别    

        如果没有指定等级,就相当于Restrict方式。  

        对于外键约束,最好是采用: ON UPDATE CASCADE ON DELETE RESTRICT 的方式。   

举例:(以 on update cascade on delete set null          为例)  

1.创建表

2.添加数据

3.修改数据 

4.删除数据 

6.8 删除外键约束

流程如下:

(1)第一步先查看约束名和删除外键约束    

        #查看某个表的约束名
    
        SELECT * FROM information_schema.table_constraints 
    
        WHERE table_name = &#39;表名称&#39;;
    
        ALTER TABLE 从表名 
    
        DROP FOREIGN KEY 外键约束名;

(     2)第二步查看索引名和删除索引。(注意,只能手动删除)    

        #查看某个表的索引名    

        SHOW INDEX FROM 表名称;      
        ALTER TABLE 从表名 DROP INDEX 索引名;

注意: 删除外键约束后,必须 手动 删除对应的索引     

举例:  

6.9 开发场景

问题     1     :如果两个表之间有关系(一对一、一对多),比如:员工表和部门表(一对多),它们之间是否     一定要建外键约束?    

        答:不是的      

问题     2     :建和不建外键约束有什么区别?    

        答:建外键约束,你的操作(创建表、删除表、添加、修改、删除)会受到限制,从语法层面受到限制。    

        例如:在员工表中不可能添加一个员工信息,它的部门的值在部门表中找不到。      

        不建外键约束,你的操作(创建表、删除表、添加、修改、删除)不受限制,要保证数据的     引用完整 性     ,只能依     靠程序员的自觉     ,或者是     在     Java     程序中进行限定     。例如:在员工表中,可以添加一个员工的信息,它的部门指定为一个完全不存在的部门。      

问题     3     :那么建和不建外键约束和查询有没有关系?    

        答:没有     

拓展:   

        在 MySQL     里,外键约束是有成本的,需要消耗系统资源。对于大并发的     SQL     操作,有可能会不适 合。比如大型网站的中央数据库,可能会     因为外键约束的系统开销而变得非常慢     。所以,     MySQL     允 许你不使用系统自带的外键约束,在     应用层面     完成检查数据一致性的逻辑。也就是说,即使你不 用外键约束,也要想办法通过应用层面的附加逻辑,来实现外键约束的功能,确保数据的一致性。     

6.10 阿里开发规范

【 强制 】不得使用外键与级联,一切外键概念必须在应用层解决。      

        说明:(概念解释)学生表中的 student_id 是主键,那么成绩表中的      student_id      则为外键。如果更新学 生表中的 student_id      ,同时触发成绩表中的      student_id      更新,即为级联更新。外键与级联更新适用于      单机低并发      ,不适合      分布式      、      高并发集群      ;级联更新是强阻塞,存在数据库      更新风暴      的风险;外键影响 数据库的      插入速度      。

7. CHECK 约束

7.1 作用

        检查某个字段的值是否符号xx     要求,一般指的是值的范围      

7.2 关键字

        CHECK      

7.3 说明:MySQL 5.7 不支持

        MySQL5.7 可以使用     check约束,但check约束对数据验证没有任何作用。添加数据时,没有任何错误或警告。    

        MySQL 8.0中可以使用check约束了     。     

7.4 添加CHECK 约束

8. DEFAULT约束

8.1 作用

        给某个字段/    某列指定默认值,一旦设置默认值,在插入数据时,如果此字段没有显式赋值,则赋值为默认值。    

8.2 关键字

        DEFAULT    

8.3 添加默认值约束

8.3.1 在 CREATE TABLE时添加默认值约束

语法格式:

        方式1:

                create table 
    表名称( 
  
                字段名 数据类型 primary key, 
  
                字段名 数据类型 unique key not null, 
  
                字段名 数据类型 unique key, 
  
                字段名 数据类型 not null default 默认值, 
  
                );

           方式2:  

                create table 
    表名称(
  
                字段名 数据类型 default 默认值 , 
    
                字段名 数据类型 not null default 默认值, 
    
                字段名 数据类型 not null default 默认值, 
    
                primary key(字段名), 
    
                unique key(字段名) 
    
                );

        说明:默认值约束一般不在唯一键和主键列上加      

举例:  

8.3.2 在 ALTER TABLE时添加默认值约束

语法格式:

        alter table 
    表名称 modify 字段名 数据类型 default 默认值; 
  
        alter table 表名称 modify 字段名 数据类型 default 默认值 not null
    ;

注:

        1.如果这个字段原来有非空约束,你还保留非空约束,那么在加默认值约束时,还得保留非空约束,否则非空约束就被删除了。

        2.同理,在给某个字段加非空约束也一样,如果这个字段原来有默认值约束,你想保留,也要在modify语句中保留默认值约束,否则就删除了。   

举例:  

8.4 删除默认值约束

语法格式:

        1.删除默认值约束,也不保留非空约束

                alter table 
    表名称 modify 字段名 数据类型 ;

        2.删除默认值约束,保留非空约束  

                alter table 
    表名称 modify 字段名 数据类型 not null
    ;

举例:  

9. 面试

面试   1   、为什么建表时,加   not null default ''   或   default 0  

        答:不想让表中出现null   值。    

面试   2   、为什么不想要   null   的值  

        答:   (1)不好比较。   null   是一种特殊值,比较时只能用专门的   is null   和   is not null   来比较。碰到运算符,通常返回null   。  

            (2)效率不高。影响提高索引效果。因此,我们往往在建表时 not null default ''   或   default 0    

面试   3   、带   AUTO_INCREMENT   约束的字段值是从   1   开始的吗?  

        在MySQL   中,默认AUTO_INCREMENT的初始 值是1,每新增一条记录,字段值自动加1   。设置自增属性(AUTO_INCREMENT)的时候,还可以指定第 一条插入记录的自增字段的值,这样新插入的记录的自增字段值从初始值开始递增,如在表中插入第一 条记录,同时指定id   值为   5   ,则以后插入的记录的   id   值就会从   6   开始往上增加。添加主键约束时,往往需要 设置字段自动增加属性。    

面试   4   、并不是每个表都可以任意选择存储引擎?   外键约束(  

FOREIGN KEY) cannot be used across engines. (The engine used by the master table and the slave table must be the same)

MySQL supports multiple storage engines. Each table can specify a different storage engine. It should be noted that foreign key constraints are used to ensure the referential integrity of the data. If the tables need to be related If foreign keys specify different storage engines, then foreign key constraints cannot be created between these tables. Therefore, the choice of storage engine is not entirely arbitrary.

Recommended learning: mysql video tutorial

The above is the detailed content of Example analysis MySQL constraint knowledge points. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete