MySQL - table constraints

Table of contents

table constraints 

1. Empty attributes

2. Default value

3. Column Description

4. zerofill

5. Primary key

6. Self-growth

7. Unique key

8. Foreign keys

9. Comprehensive case


table constraints 

        It is the data type that really constrains the field, but the data type constraint is very single, and some additional constraints are needed to better ensure the legality of the data and ensure the correctness of the data from the perspective of business logic. For example, a field is email, and the requirement is unique. (Your email must be unique, there can be no repetition)
There are many constraints on the table, here are the following:
null/not null default , comment , zerofill primary key auto_increment unique key  

1. Empty attributes

  • An empty property has two values, null and not null .
  • The default fields of the database are basically allowed to be empty, but in actual development, we should try our best to ensure that the fields are not empty, because empty values ​​cannot participate in operations.

Through select, you can see that the value of null is null. Since the null value cannot participate in the operation, the value obtained after adding one to the null value is still null.

If you want to make a field not allowed to be empty, you can set the not null attribute         for the corresponding field when creating the table . For example, we create a class table, which contains the class name and the classroom where the class is located. If you do not want these two fields to be empty when inserting data, you can set the not null attribute for these two fields when creating the table.

Standing in normal business logic:

  • If the class doesn't have a name, you don't know which class you are in
  • If the classroom name can be empty, I don’t know where the class is

Therefore, when we design a database table, we must restrict it in the table, and data that meets the above conditions cannot be inserted into the table. This is the "constraint".

Check the table structure after creating the table, you can see that these two fields are not allowed to be empty. as follows:

When inserting a record into the table, only when these two fields are not empty can the insertion be successful, otherwise the insertion will fail. as follows:

2. Default value

Default value: A certain type of data will often have a specific value, which can be specified at the beginning. When real data is needed, the user can selectively use the default value.

        For example, create a user table that contains the user's name, age, and gender. Set the user's age to 18 by default and the user's gender to male by default. as follows: 

Check the table structure after creating the table, you can see that the default value has been set successfully. as follows:

When inserting data into the table, if the user's age or gender is not specified, the given default value will be used, and if specified, the user-specified value will be used. as follows:

Set not null and default to a field at the same time 

  • Once a default value is set for a field, the field will not have a null value, because even if the value of the field is not specified when inserting data, it will be filled with the default value of the field.
  • The purpose of setting the not null attribute for a field is to constrain the field cannot be empty, so after a field is set with the default attribute, it is meaningless to set the not null attribute.

3. Column Description

Column description: comment, which has no actual meaning, is specially used to describe the field, and will be saved according to the table creation statement for programmers or DBAs to understand. (You can understand it as a comment)

 After the table is created, use the following SQL statement to see the relevant details of the table creation, including column descriptions. as follows:

#查看创建表时详细的细节
show create table 表名

4. zerofill

The number in parentheses behind the numeric type represents the display width. After the zerofill attribute is set for the corresponding numeric type, if the width of the data is smaller than the set width, it will be automatically filled with 0.

For example, create a table that contains two columns of integer data, a and b, and set their display width to 8, but do not set the zerofill attribute. as follows: 

Insert a record into the table, indicating that the values ​​of a and b are both 10. Since we have not set the zerofill attribute for the a and b fields, when viewing the data in the table, all are displayed as 10, and the concept of width is not displayed. as follows:

Modify the table structure and add the zerofill attribute to column a. Since the display width of the data in column a is 8, you can see that the data in column a with a width of less than 8 digits is automatically filled with 0 in front of the data in the table. as follows:

        The function of the zerofill attribute is to display the data in a specific way, and the underlying storage method of the data has not changed.

5. Primary key

Primary key: The primary key is used to uniquely constrain the data in the field. It cannot be repeated or empty. There can be at most one primary key in a table; the column where the primary key is located is usually an integer type.

For example, create a student table, which contains the student's student number and name. Since the student's student number will not be repeated, it can be set as the primary key. as follows: 

After the table is successfully created, check the table structure, and you can see that PRI appears in the Key column corresponding to the id, which means that we have successfully set the student number as the primary key of this table. In addition, although the not null attribute was not set for the student number when creating the table, since the primary key itself cannot be empty, the id cannot be empty by default.

The so-called primary key constraint is that the primary key field of the record inserted into the table cannot be repeated. If the primary key of the inserted record is the same as the primary key of the existing record in the table, the insertion will fail due to a primary key conflict. as follows:

Use the following SQL to delete the primary key of the specified table, because a table has only one primary key, so when deleting the primary key, you only need to specify the primary key of the table to be deleted. For example, after deleting the primary key of the student table and checking the table structure, you can see that the PRI of the Key column corresponding to the id is gone. as follows:

alter table 表名 drop primary key

For the table that has been created, use the following SQL to set the specified column as the primary key, but it should be noted that only the columns whose values ​​are not empty and not repeated can be set as the primary key. For example, reset the student number as the primary key of the student table and then check the table structure. You can see that the PRI of the Key column corresponding to the id is back. as follows:

alter table 表名 add primary key(列名)

composite primary key

When creating a table, after all the fields, the primary key (primary key field list) can also be used to create a primary key. If there are multiple fields as the primary key, a composite primary key can be used.

 The following two columns form the primary key

 When the composite primary key is inserting data, if only one of them conflicts, it will not be affected, and all conflicts will affect the insertion:

#删除指定表的复合主键
alter table 表名 drop primary key

#用多个列形成复合主键
alter table 表名 add primary key(多个列名)

6. Self-growth

auto_increment: When the corresponding field does not give a value, it will be automatically triggered by the system, and the system will operate from the existing maximum value in the current field + 1 to get a new and different value. Usually used in conjunction with the primary key as a logical primary key.
Self-growth features:
  • Any field needs to be self-increased, provided that it is an index (the key column has a value)
  • The self-incrementing field must be an integer
  • A table can only have at most one self-growth

  1. If the value of the auto-increment field is not specified when inserting the first record into the table, the value of the auto-increment field will start from 1 by default.
  2. If the value of the self-incrementing field is not specified when inserting records into the table later, the value of the self-increasing field will be incremented sequentially.
  3. Of course, when inserting a record, you can also specify the value of the self-increasing field. At this time, the value will be used for insertion, but note that the specified value cannot be the same as the existing id value in the table.
  4. After that, if you do not specify the value of the self-increasing field when inserting records into the table, then the value of the self-increasing field will find the maximum value from the id column, and add the value obtained by adding one to the maximum value as the value of the self-increasing field. insert.

7. Unique key

        There are often many fields in a table that require uniqueness, and the data cannot be repeated, but there can only be one primary key in a table: a unique key can solve the problem that multiple fields in a table require unique constraints. The essence of the unique key is similar to that of the primary key. The unique key is allowed to be empty, and more than one can be empty. The empty field is not compared for uniqueness.
The difference between a unique key and a primary key:
We can simply understand that the primary key is more about identifying uniqueness. The unique key is more to ensure that in business, it will not be duplicated with other information.

For example, create a student table, which contains the student's id, name, and phone number. We choose id as the primary key, but at the same time, each student's phone number should also have a unique constraint, so the phone number should be set as a unique key. as follows: 

Check the table structure after the table is created, and you can see that the UNI flag appears in the Key column of tel, which indicates that tel has been successfully set as the unique key. as follows:

When inserting a record into the table, if the phone number in the inserted record is duplicated with the phone number already recorded in the table, the insertion will fail due to a unique key conflict. as follows:

In addition, the record inserted into the table may not specify the value of the unique key field. At this time, the field is empty by default and no uniqueness comparison is performed. as follows:

8. Foreign keys

The foreign key is used to define the relationship between the main table and the slave table : the foreign key constraint is mainly defined on the slave table, and the master table must have a primary key constraint or a unique constraint. When the foreign key is defined, it is required that the foreign key column data must exist in the primary key column of the main table or be null.

grammar:

foreign key (字段名) references 主表(列)

For example, first create a class table as the main table, which contains the class id and class name, and set the class id as the primary key. Then create a student table as a secondary table, which contains the student's id, name, and the id corresponding to the student's class, and set the class id column in the student table as a foreign key, which is associated with the class id column in the class table. as follows:

After the table is created, check the table structure of the student table, and you can see that the Key column corresponding to the class id in the student table has a MUL flag, which indicates that class_id has been successfully set as a foreign key. as follows:

To demonstrate foreign key constraints, we first insert two records into the class table. as follows:

At this time, when inserting a record into the student table, if the class id corresponding to the inserted record exists in the class table, or the inserted class id is null, then the insertion is allowed at this time. as follows:

But if the class id corresponding to the record inserted into the student table is 103, it means that the class corresponding to the record inserted into the student table does not exist, and the insertion will fail at this time, which is the foreign key constraint. as follows:

At this time, if you insert the class information with the class id of 103 into the class table, and then insert the above record into the student table, then the insertion is allowed. as follows:

Foreign key constraints:

  • Theoretically, even if we do not set foreign keys after we create the class table and student table, we already have foreign keys semantically, but in this way we cannot guarantee the correctness of the class id in the subsequent records inserted into the student table.
  • And after we set the class id in the student table as a foreign key, the foreign key constraint can ensure that only records with the class id in the class table can be inserted into the student table, otherwise the insertion will fail.
  • The essence of actually establishing a foreign key is to hand over the correlation to MySQL for review, and tell MySQL in advance the constraint relationship between tables. When users insert data that does not conform to business logic, MySQL will not allow you to insert.

9. Comprehensive case

There is a store's data, which records customers and shopping conditions, and consists of the following three tables:
  • Goods (product number goods_id, product name goods_name, unit price unitprice, product category category, supplier provider)
  • Customer customer (customer number customer_id, name name, address address, email address, gender sex, ID card_id)
  • Purchase purchase (purchase order number order_id, customer number customer_id, product number goods_id, purchase quantity nums)
Require:
  • Primary and foreign keys for each table
  • Customer's name cannot be empty
  • Email address cannot be repeated
  • Customer's gender (male, female)

First of all, we need to create a database first, and then complete the creation of these three tables in the database. as follows: 

When creating a product table, set the product number as the primary key and set it as a self-increasing field. The attributes of other fields are not required and can be set reasonably by yourself. as follows:

 After the product table is created, view the table structure as follows:

When creating the customer table, set the customer number as the primary key and set it as a self-increasing field, then set the not null attribute for the name, set the mailbox as a unique key, set the gender as an enum type and only provide male and female gender options, In addition, although the title does not require the ID card, normally the ID card should also ensure uniqueness, and it is best to set it as a unique key. as follows:

After the customer table is created, view the table structure as follows:

When creating the purchase table, set the order number as the primary key and it can be set as a self-increasing field, but you need to set the customer number and product number as foreign keys, which are respectively associated with the customer number and product number in the customer table and product table , use foreign key constraints to ensure that the customer number and product number of each order exist. as follows:

After the purchase table is created, view the table structure as follows:

 

Guess you like

Origin blog.csdn.net/sjsjnsjnn/article/details/128923526