[mysql]——Table constraints

Table of contents

Preface

(1) Empty attribute

(2) Default value

(3) Column description

(4) zerofill

(5) Primary key

(6) Self-growth

(7) Unique key

(8) Foreign keys

Summarize


Preface

What really constrains fields is the data type, but the data type constraints are very single. 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, one field is email, and it is required to be unique.
 

definition:

  • Therefore, in a database, table constraints (cyonstraint) are rules used to define rules and restrictions for data in the table . They are used to ensure data integrity and consistency and to prevent illegal data insertion, update, or deletion. By defining constraints, you can enforce specific conditions and regulations to ensure the correctness and quality of your data.

Common table constraint types include:

  1. Primary Key Constraint: Defines a column or a set of columns to uniquely identify each row in the table. Primary keys are used to ensure uniqueness and data integrity.

  2. Unique Constraint : Ensures that all values ​​in a column or a group of columns are unique, but can have null values. It prevents duplicate data.

  3. Foreign Key Constraint: used to ensure the integrity of relationships between tables. It defines references to primary keys or unique keys in other tables and can be used to establish associations between tables.

  4. Not Null Constraint : Specifies that a column is not allowed to contain null values ​​(NULL). It ensures that a value must be provided for the column.

  5. Default Constraint: Defines a default value for a column. If no value for the column is provided when inserting a new row, the default value will be used.

  6. Check Constraint : Define the value range or condition of a column. It is used to limit the data that the column can accept.

These constraints can be applied to columns individually, to multiple columns, or in combination. By using table constraints, data can be validated and restricted at the database level to improve data integrity and consistency.


(1) Empty attribute

  1. Two values: null (default) and not null (not empty)
  2. The default fields in the database are basically empty. However, during actual development, try to ensure that the fields are not empty, because empty data cannot participate in calculations .

 

Case:
Create a class table, including the class name and the classroom where the class is located.
Standing in the normal business logic:

  1. If the class doesn't have a name, you don't know which class you are in
  2. If the classroom name can be empty, we don’t know where the class is held.

Therefore, when we design the database table, we must impose restrictions in the table. Data that meets the above conditions cannot be inserted into the table. This is "constraint".
 

  •  When inserting data, there is no classroom data and the insertion fails:

 


(2) Default value

In MySQL, you can use Default Constraint to specify default values ​​for columns in a table. This way, when inserting a new row, if no specific value is provided for that column, the default value will be used automatically.

Here is an example that creates a table with a default value constraint users:

  • In the above example, name the and email columns are both defined to have default values. When inserting data, if no value is provided for the specified column, the default value will be used automatically. 

The effect of the default value: when the data is inserted, the field is not assigned a value, and the default value is used
 

 

Secondly. If you want to modify the default value of a column in an existing table, you can use ALTER TABLEthe command:

 


(3) Column description

In MySQL, you can use column description (Column Description) to add descriptive information for the columns in the table. Column Description is an optional metadata attribute used to provide more details about the column, such as its purpose, meaning, or any other relevant description.

Here is an example, creating a t1 table with column descriptions:

 

Annotation information cannot be viewed through desc:
 

 You can see through show:

 

 


(4) zerofill

In MySQL, ZEROFILL a table constraint that pads a column storing a numeric type with zeros to a specified number of digits. It causes the value to occupy a fixed number of digits when displayed, padding the gaps with zeros when necessary.

To use  ZEROFILL constraints, you need to use them with numeric columns such as  INT, BIGINT, FLOAT, DOUBLE etc. In the column definition,  ZEROFILL enable zero padding by adding the keyword and specifying the desired number of digits.

 You can see int(10), what does this mean? Integers are not 4-byte codes? What does this 10 represent? In fact, without the zerofill attribute, the numbers in brackets are meaningless. Columns a and b are the data inserted previously, as follows:
 

 

But after adding the zerofill attribute to the column, the displayed results are different. Modify the attributes of the t2 table:
 

 

Add the zerofill attribute to column a, then search, and return the following results:
 

【in conclusion】 

  •  This time you can see that the value of a has changed from the original 1 to 00001. This is the role of the zerofill attribute. If the width is less than the set width, 0 will be automatically filled. It should be noted that this is only the last displayed result, and the actual value stored in MySQL is still 1.

Why is this? We can use the hex function to prove:

 

 

  • It can be seen that the internal storage of the database is still 1,00001, which is just a formatted output after setting the zerofill attribute.
     

Immediately after, we change the value in int() in a to 5, and then perform the insertion operation:

 The insertion operation is as follows:

【in conclusion】 

 When we look at the current table, we can find a problem:

  1. When we insert less than 5 digits, the missing ones are filled with 0;
  2. When it exceeds five digits, the system will output the inserted data as it is.

Finally, the answer is why the default value we create is int(10)?

  1. First of all, because the type we created is an unsigned type, and the value range of unsigned is [0, 2^32-1];
  2. The numerical range of 2^32-1 is a 10-digit integer, so when we look at it, the default is int(10)

 Summary : Use  ZEROFILL constraints to facilitate number display and formatting, especially when a fixed number of identifiers or encodings are required.


(5) Primary key

In MySQL, a primary key constraint (Primary Key Constraint) is used to define one or more columns in a table as constraints that uniquely identify each row in the table. A primary key constraint is an important constraint used to ensure the uniqueness and integrity of data.

Primary key constraints have the following characteristics:

  1. Uniqueness : The value of the primary key must be unique in the entire table, that is, the primary key value of each row is different.
  2. Non-nullability : The value of the primary key column cannot be NULL, that is, the primary key column cannot be empty.
  3. Unique identification : The primary key is used to uniquely identify each row in the table, so as to facilitate accurate location and association of data in the table.

【Case】

  • When creating a table, specify the primary key directly on the field.
     

  •  Primary key constraint : The field corresponding to the primary key cannot be repeated. Once repeated, the operation fails.

  •  When the table is created but there is no primary key, you can add the primary key again

 

  • Delete primary key
     

 

  • Composite primary key
     

When creating a table, use primary key (primary key field list) to create a primary key after all fields. If there are multiple fields
as primary keys, you can use a composite primary key.
 

 

 

By specifying primary key constraints, you can ensure that the data in the table has a unique identifier, and verify and protect the integrity of the data.


(6) Self-growth

In MySQL, Auto_increment is a constraint on a table's columns that allows the database to automatically assign a unique increment value to each newly inserted row. Auto-increasing columns are often used as primary key columns for a table to ensure that each newly inserted row has a unique and incrementing identifier.

auto_increment: When the corresponding field does not give a value, it will be automatically triggered by the system. The system will operate from the maximum value + 1 in the current field to obtain a new and different value. Usually used in conjunction with the primary key as a logical primary key.


Characteristics of self-growth:

  1. For any field to be auto-increasing, the premise is that it is an index (the key column has a value)
  2. Autoincrement fields must be integers
  3. A table can have at most one self-increment
     

【Case】

 

Get the value of the last inserted AUTO_INCREMENT after insertion (batch insertion gets the first value)
 

【Index】

In a relational database, an index is a separate, physical storage
structure collection of one or several column values ​​in a table and the corresponding pointer. A list of logical pointers to the data pages in the table that physically identify these values. The index is equivalent to the table of contents of a book. You can quickly find the required content based on the page numbers in the table of contents.


Indexes provide pointers to data values ​​stored in specified columns of a table, and then sort these pointers according to a sort order that you specify.
The database uses an index to find a specific value and then points forward to find the row containing that value. This allows SQL statements corresponding to the table to execute faster and allows quick access to specific information in the database table.

Auto-increment constraints make it easy to generate and maintain rows with unique identifiers, reducing the work of manually providing identifiers and possible conflicts. Auto-increasing columns are often used as primary key columns to enable efficient data insertion and lookup.


(7) Unique key

In MySQL, a unique key (Unique Key) is a constraint used to ensure that the value of a column or combination of columns in a table is unique in the entire table. A unique key constraint is similar to a primary key constraint, but it allows null values ​​(NULL) and can be applied to multiple columns.

Unique key constraints have the following characteristics:

  1. Uniqueness : The value of the unique key must be unique in the entire table, that is, the unique key value of each row cannot be repeated with the unique key value of other rows.
  2. Can contain NULL values : Unique key columns are allowed to contain NULL values. Because NULL is not equal to NULL, two rows containing NULL values ​​do not violate the unique key constraint.

Regarding the difference between unique key and primary key:

  1. We can simply understand that the primary key is more about identifying uniqueness;
  2. The unique key is more to ensure that in business, it will not be duplicated with other information.
     

 

  • Unique constraints cannot be repeated, but can be empty:
     

 

By using unique key constraints, you can ensure that a column or combination of columns in a table has a unique value, ensuring data integrity and consistency. Compared to primary key constraints, unique key constraints allow null values ​​and can be applied to multiple columns, providing greater flexibility.


(8) Foreign keys

In MySQL, a foreign key is a constraint used to ensure data integrity and consistency between tables. Foreign keys define relationships between tables based on the relationship between column values ​​in one table and column values ​​in another table.

Foreign key constraints have the following characteristics:

  1. Association : Foreign key constraints are used to define associations between tables, in which column values ​​in one table (called the child table) must exist in column values ​​in another table (called the parent table).
  2. Data integrity : Foreign key constraints ensure that the associated data exists in the parent table, thereby maintaining data integrity and consistency. It prevents invalid or inconsistent data from being inserted into child tables.
  3. Optional : Foreign key columns can be empty or contain NULL values, but if they contain a value, the value must exist in the parent table.

To use foreign key constraints, the following conditions need to be met:

  1. There must be associated columns between the child table and the parent table, and the columns in the child table are used to reference the columns in the parent table.
  2. The related column in the parent table must have a unique constraint or a primary key constraint.

grammar

  • foreign key (field name) references main table (column)

【Case】

 Design the schematic diagram above:

  • Create the primary key table first
     

 

  • Create the slave table again:

  •  Insert data normally:

  •  Insert a student with class number 30. Because there is no such class, the insertion is unsuccessful:

  •  Insert the class id as null. For example, a student comes and has not yet been assigned a class:

  •  How to understand foreign key constraints:

First of all, we admit that a lot of data in this world is correlational.


Theoretically, in the above example, we do not create foreign key constraints, we can create the student table and class table normally, and we have all the required fields.


At this point, what problems may arise during actual use?

  1. Is it possible that the inserted student information contains a specific class, but the class is not in the class table?
  2. For example, there are only 26 classes in one grade, but there are actually 27 students in the class (this class does not currently exist). This is obviously a problem.


Because the two tables are related in business at this time, but there is no constraint relationship established in business, then problems may occur.


The solution is accomplished through foreign keys . The essence of establishing foreign keys is to hand over the correlation to mysql for review, and tell mysql the constraints between tables in advance. Then when the user inserts data that does not comply with the business logic, mysql will not allow you to insert.
 

By using foreign key constraints, you can ensure the relationship between tables and maintain data integrity. It prevents the insertion of invalid reference data or data that causes inconsistency. Foreign key constraints are an important tool for maintaining relationships between tables and help ensure the consistency of associated data.


Summarize

The above is all about the constraints of mysql tables. Next, let’s briefly review the content of this article! ! !

  1. In MySQL, table constraints are used to define and protect the integrity and consistency of data.
  2. These constraints can be specified when the table is created, or can be added, modified, or deleted using the ALTER TABLE statement;
  3. They help ensure that the data in the table meets specific rules and association conditions, providing data consistency and integrity guarantees;
  4. Based on actual needs and data model design, different types of constraints can be used in combination to achieve the required business logic and data restrictions.

At this point, the explanation of this article is complete. Thank you for watching and supporting! ! !

 

Guess you like

Origin blog.csdn.net/m0_56069910/article/details/132243061