MySQL constraint control


constraint control

insert image description here

Data integrity constraints (referred to as "constraints") are data detection rules enforced on tables and fields to prevent irregular data from entering the database. When we perform DML operations on data, the database management system (DBMS) will automatically detect the data according to the constraints we set to ensure the integrity and accuracy of data storage.

Integrity constraints are divided into four categories: entity integrity constraints, domain integrity constraints, referential integrity constraints, and user-defined integrity constraints.

  • Entity integrity constraints: used to identify each record in the table represents an entity, such as primary key constraints;
  • Domain integrity constraints: constraints for cells, such as non-null constraints, etc.;
  • Referential integrity constraint: refers to the corresponding relationship between multiple tables. When performing operations such as data insertion, update, and deletion in one table, the DBMS will compare it with another table to avoid irregular operations and ensure the integrity of data storage. properties, such as foreign key constraints;
  • User-defined integrity constraints: users define them according to actual requirements. When performing operations such as data insertion and update, the DBMS will check whether the data meets the constraints in the check constraints to avoid operations that do not meet the conditions, so as to ensure the integrity of data storage. Accuracy, such as check constraints (not supported by MySQL, supported by Oracle).

There are 6 types of constraints supported in MySQL, namely: non-null constraints, primary key constraints, default value constraints, unique constraints, foreign key constraints, and custom check constraints.

According to where the constraints are added, we can divide constraints into two categories:

  • Column-level constraints: add constraints directly after the defined field names and types. But this method only supports default value constraints, non-null constraints, primary key constraints, and unique constraints.
  • Table-level constraints: add after each field is defined. Table-level constraints do not support not-null constraints and default value constraints.

not-null constraint

The statement used to create a not-null constraint is NOT NULL, and its function is to ensure that the field cannot be empty. When looking at the structure of the student table, there is a column named Null in the table header, which indicates whether a non-null constraint has been added to the field. We created the professional information table when talking about 3NF, and set the professional field to be non-empty in the form of column-level constraints. Its SQL statement is as follows:

create table specialty(
specialty_name varchar(20) not null,
specialty_college varchar(20)
);

Output result:
insert image description here

Use desc to view the table structure:

desc specialty;

Output result:
insert image description here

When we insert data, if the field value is empty, an error will occur, as shown below:

insert into specialty values(null,'计算机学院');

Output result:
insert image description here

One thing to note here is the difference between a null value (NULL) and an empty string ('').

  • There are different methods of query determination: to determine whether a value is null, you can use is null or is not null; to determine whether a value is an empty string, use = and <> to operate.
  • Whether to participate in the operation: the empty value (NULL) does not participate in the operation, but the empty string can.
  • Whether to take up space: a null value (NULL) takes up space, while an empty string ('') does not take up space. So when designing tables, our fields should be set as not null constraints as much as possible.

primary key constraint

Create a primary key constraint using the PRIMARY KEY statement, whose role is to ensure that the value of the field is unique. Only one primary key can be created for each table, which is the unique identifier of the table and has its own non-empty attribute by default. Create a primary key constraint by modifying the table. Modify the student table to make student_id the primary key. The specific implementation of the SQL statement is as follows:

alter table student modify student_id int primary key;

Output result:
insert image description here

Use the desc command to view the table structure, if PRI appears in the Key column, the setting is successful.

desc student;

Output result:
insert image description here

After the primary key is successfully set, its uniqueness and non-nullness must be considered when inserting data. The records in the current table are:

select * from student;

Output result:

insert image description here

When inserting a new record whose student_id is 1, an error message will be given, as shown below:

insert into student values(1,'小刘','大数据专业');

Output result:
insert image description here

The primary key cannot be repeated, and we need to know whether the primary key of the record to be inserted already exists when inserting data. It is easier to confirm if the data is small and in order; but if there is a lot of data and out of order, it will become very troublesome to confirm the duplicate primary key.

Is there a way to keep the primary key unique automatically when we insert a record?

The answer is to use the auto-increment sequence (auto_increment). A table has and can only have one auto-increment sequence. The auto-increment sequence is generally used in conjunction with the primary key, and the type of the auto-increment sequence field is an integer.

Modify the primary key of the student table so that student_id has an auto-increment attribute. Use the drop statement to delete the existing primary key features. The SQL statement is as follows:

alter table student drop primary key;

Output result:
insert image description here

Set student_id as the primary key again, and it has an auto-increment attribute. Its SQL statement is as follows:

alter table student modify student_id int primary key auto_increment;

Output result:
insert image description here

The advantage of using self-growth is that we don't have to worry about the duplicate primary key. It should be noted that when inserting data, the value of the self-growth field is replaced by null, as shown below:

insert into student values(null,'小赵','计算机专业');

Output result:
insert image description here

search result:

select * from student;

Output result:
insert image description here

default constraint

The statement used to create a default value constraint is DEFAULT, which ensures that the field always has a value. Set the major of all students to be big data major by default, and the SQL statement is as follows:

alter table student modify student_specialty varchar(20) default '大数据专业';

Output result:
insert image description here

The following statement specifies no value for the student_specialty field:

insert into student(student_id,student_name) values(null,'小蓝');

Due to the existence of the default value constraint, even if no value is specified for the student_specialty field, the system will automatically insert the default value. View the inserted results as follows:

select * from student;

Output result:
insert image description here

unique constraint

The statement used to create a unique constraint is UNIQUE, which ensures the uniqueness of field values. The same point of the unique constraint and the primary key constraint is to ensure the uniqueness of the value. The difference is that a unique constraint allows multiple occurrences in a table, while a primary key constraint can only have one. Create a unique constraint for the professional name field in the professional information table that satisfies 3NF, using the table-level constraint method, the created SQL statement is as follows:

create table specialty(
specialty_name varchar(20),
specialty_college varchar(20),
unique(specialty_name)
);
insert into specialty
values
('大数据专业','计算机学院'),
('计算机专业','计算机学院');

Use the desc command to view the table structure, and if UNI appears in the Key column, the setting is successful.

desc specialty;

Output result:
insert image description here

Use the desc command to see that the key column of the row where the specialty_name is located displays "UNI", which means that the unique constraint is set successfully.

foreign key constraints

The statement used to create a foreign key constraint is FOREIGN KEY, which is used to limit the relationship between the two tables and ensure that the value of the field in the table comes from the associated table. Foreign key constraints must be defined using table-level constraints.

Set student_specialty in the student table as a foreign key to associate specialty_name in the specialty table. Its SQL statement is as follows:

alter table student add foreign key(student_specialty) references specialty(specialty_name);

Output result:
insert image description here

The keyword references connects the associated tables. It should be noted that when the main table is inserting records, the value of the foreign key must be found in the associated column of the associated table, otherwise the information will fail to be inserted. The data in the specialty table is as follows:

select * from specialty;

Output result:
insert image description here

When inserting records in the student table, the value of the field student_specialty can only be one of these two, otherwise an error will be reported, as shown below:

insert into student values(null,'小兰','管理专业');

Output result:
insert image description here

Guess you like

Origin blog.csdn.net/m0_62617719/article/details/130942605