MySQL database - constraints

insert image description here

foreword

MySQL Constraints is a specification for defining and enforcing data integrity rules in relational databases. They define the constraints of the data in the database tables to ensure the consistency and validity of the data.

Today I will share with you the following constraints:

  1. Primary key constraint (primary key)
  2. Self-growth constraints (auto_incremnet)
  3. Not null constraint (not null)
  4. Unique constraint (unique)
  5. Default constraint (default)
  6. Zero Fill Constraints (zerofill)
  7. Foreign key constraints (foreign key)

primary key constraint

A MySQL primary key constraint is a type of constraint used to ensure the uniqueness and integrity of data in a table. A primary key is a combination of one or more columns that identifies a unique record in a table. A primary key constraint must satisfy the following conditions:

  1. Uniqueness: The value of the primary key must be unique across the entire table. No two records can have the same primary key value.

  2. Non-nullness: The value of the primary key cannot be empty. Every record must have a non-null primary key value.

  3. Unique identifier: The primary key acts as a unique identifier for each record in the table. It can be used to find, update and delete records in a table.

When creating a primary key constraint, the system will create a corresponding unique index on the column and column combination by default.

create primary key

There are two forms of primary key, one is a single-column primary key, and the second is a joint primary key.

single column primary key

There are two ways to create a single-column primary key in MySQL: one is to specify the primary key after the corresponding column when we create the table, and the other is to specify the primary key after we create the column

Specify the primary key when creating the table

create table student1(id int primary key,name varchar(20));

insert image description here

Specify the primary key after creating the column

create table student1(id int,name varchar(20),constraint pk1 primary key(id));

Here contrain pk1can be omitted, this is primary keythe complete way of writing, pk1 is the constraint name, which can be customized.

insert image description here

combined primary key

A joint primary key refers to using multiple columns in a table as a primary key. A certain column may be the same, but all corresponding columns are not allowed to be the same, and null cannot be contained.

There is only one way to create a composite primary key:
create table 表名(列名1 类型,列名2 类型,列名3 类型,constraint pk2 primary key(列名1,列名2));

create table student1(id int,name varchar(20),constraint pk1 primary key(id,name));

insert image description here

When a certain column is duplicated, data can be inserted, but when the corresponding columns of the combined primary key are all the same, the insertion fails.

insert into studen1 values(1,'张三');
insert into studen1 values(1,'李四');

insert image description here

insert into student1 values(2,'王五');
insert into student1 values(2,'王五');

insert image description here

None of the columns can appear null

insert into student1 values(3,null);

insert image description here

Specify the primary key by modifying the table structure

We can specify the primary key after the table is createdalter table 表名 add primary key(列名);
alter table 表名 add primary key(列名1,列名2)

create table student1(id int,name varchar(20));
alter table student1 add primary key(id);

insert image description here

create table student1(id int,name varchar(20));
alter table student1 add primary key(id,name);

insert image description here

drop primary key constraint

When you don't want to use the primary key, you can use to alter table 表名 drop primary key;delete the primary key.
insert image description here
When deleting the primary key, whether you have a single-column primary key or a combined primary key, usealter table 表名 drop primary key;

auto increment primary key constraint

A MySQL auto-increment primary key is a special type of primary key constraint that uses an auto-increment value to generate a unique identifier for each newly inserted record. An auto-incrementing primary key allows records to be inserted into a table without manually specifying the primary key value and ensures that each record has a unique identifier.

Using an auto-increment primary key has the following advantages:

  1. Simplified data insertion: No need to manually specify the primary key value, the database will automatically assign a unique primary key value to each newly inserted record. This simplifies the coding of insert operations and reduces the possibility of conflicts.

  2. Uniqueness guarantee: The value of the auto-increment primary key is unique in the table, avoiding the problem of manual management of primary key conflicts.

  3. Fast access: The value of the auto-increment primary key is incremented sequentially, which helps to improve the performance of query and index operations based on the primary key.

Features of auto-increment primary key:

  • By default, the initial value of auto_increment is 1, and every time a new record is added, the field value will automatically increase by 1
  • Only one field in a table can use the auto_increment constraint, and the field must have a unique index to avoid duplication of sequence numbers (that is, the primary key or part of the primary key).
  • Fields constrained by auto_increment must have the NOT NULL attribute.
  • Fields constrained by auto_increment can only be integer types ( TINYINT , SMALLINT , INT , BIGINT , etc.
  • The maximum value of an auto_increment constraint field is constrained by the data type of the field. If the upper limit is reached, auto_increment will fail.

Create an auto-increment primary key

Because the auto-increment primary key is a special primary key, the primary key and the auto-increment primary key need to be specified in the same column.

create table 表名 (列名1 类型 primary key auto_increment,列名2 类型);

create table student1(id int primary key auto_increment,name varchar(20));

insert image description here
When a column is set as an auto-increment primary key, when we insert data, we can pass in null, and the data in this column will default to auto-increment data starting from 1 (when no auto-increment initial value is defined).

insert into student1 values(null,'张三');

insert image description here

Assign an initial value to the auto-increment primary key
We can specify where the auto-increment data starts and specify the initial value for the auto-increment data.

create table student1(id int primary key auto_increment,name varchar(20)) auto_increment=值;

create table student1(id int primary key auto_increment,name varchar(20)) auto_increment=100;
insert into student1 values(null,'张三');

insert image description here

Assign an initial value to the auto-increment primary key after creating the table

alter table 表名 auto_increment=初始值;

create table student1(id int primary key auto_increment,name varchar(20));
alter table student1 auto_increment=100;
insert into student1 values(null,'张三');

insert image description here

Delete and truncate changes in auto-increment columns after deletion

  • After deleting data, the automatic growth starts from the breakpoint
  • Autogrow after truncate data from default starting value
insert into student1 values(null,'张三');
insert into student1 values(null,'李四');
delete from student1;
insert into student1 values(null,'王五');

insert image description here

truncate student1;
insert into student1 values(null,'李华');

insert image description here

not-null constraint

A MySQL not-null constraint is a type of constraint used to ensure that a column in a table does not allow null values ​​(NULL). A not-null constraint requires that the column must contain valid values ​​when inserting or updating data. Not-null constraints can be applied to a single column or to multiple columns.

Create a not-null constraint

There are two ways for MySQL to create non-null constraints: the first is that we specify non-null constraints when we create tables,
create table 表名(列名1 类型 not null,列名2 类型);and the second is that we specify non-null constraints after we create tablesalter table 表名 modify 列名 类型 not null;

create table student1(id int not null,name varchar(20));
desc student1;

insert image description here

create table student1(id int,name varchar(20));
alter table student1 modify id int not null;
desc student1;

insert image description here

insert into student1 values(null,'张三');

insert image description here

remove not-null constraint

alter table 表名 modify 列名 类型;

alter table student1 modify id int;
desc student1;

insert image description here

unique constraint

A MySQL unique constraint is a type of constraint used to ensure that the data in one or more columns in a table is unique. A unique constraint ensures that the values ​​in a column are unique, but allows one or more null values ​​(NULL).

Create a unique constraint

There are also two ways to create a unique constraint in MySQL: specify a unique constraint when creating a table: create table 表名(列名1 类型 unique,列名2 类型);specify a unique constraint after creating a table: alter table 表名 add constraint unique_pn unique(列名);here the constraint constraint name is not omitted, in preparation for the subsequent deletion of the unique constraint.

create table student1(id int constraint unique_pn unique,name varchar(20));
insert into student1 values(1,'张三');
insert into student1 values(1,'李四');

insert image description here

create table student1(id int,name varchar(20));
alter table student1 add constraint unique_pn unique(id);
insert into student1 values(1,'张三');
insert into student1 values(1,'李四');

insert image description here

Remove the uniqueness constraint

When deleting the unique constraint, we need to use the constraint name we defined earlier.
alter table 表名 drop index 唯一约束名

alter table student1 drop index unique_pn;

If you did not define a unique constraint name before, then the default is the column name you set the unique constraint on.

default constraints

The MySQL default constraint is a default value rule defined for a column in the table when the table is created. When inserting a new record, MySQL automatically applies a default value to the column if no value is explicitly provided for that column. A default constraint can be a concrete value, or an expression, function, or system variable.

Create default constraints

Our MySQL default default constraint is null, so we can also set the default value ourselves. Specify default constraints while creating the table: create table 表名(id int default 默认值,name varchar(20) default 默认值);specify default constraints after the table is createdalter table 表名 modify 列名 default 默认值;

create table student1(id int,name varchar(20) default '无名氏');
desc student1;

insert image description here

alter table student1 modify name default '无名氏';

insert image description here

Delete the default constraint (change to null as the default value)

alter table 表名 类型 modify 列名 default null;

alter table student1 varchar(20) modify name default null;

insert image description here

Zero Padding Constraint

The MySQL zero-fill constraint is a constraint for integer data columns, which defines how to handle the case of insufficient numerical length when inserting or updating data. When the numerical length of an integer data column is less than the defined length, MySQL will use zero padding to make up.

  • When inserting data, when the length of the value of the field is less than the defined length, the corresponding 0 will be added in front of the value
  • zerofill defaults to int(10)
  • When using zerofill, the unsigned (unsigned) attribute is automatically added by default. After using the unsigned attribute, the value range is twice the original value. For example, signed is -128 ~ +127, unsigned is 0 ~ 256

Create a zero-fill constraint

create table 表名(列名1 类型(指定宽度) zerofill,列名2 类型);

create table student1(id int(5) zerofill,name varchar(20));
insert into student1 values(1,'张三')

insert image description here

Remove zero padding constraints

alter table 表名 modify 列名 类型;

alter table student1 modify id int;
insert into student1 values(2,'李四');

insert image description here
The zero-fill constraint is only filled with 0 when it is displayed, but the content in the table does not change.

foreign key constraints

In school, we all know that each student has a corresponding class, and this similar relationship can also be reflected in MySQL.

Foreign keys are used to relate primary keys or unique keys of other tables

Create foreign key constraints

create table 表名 (列名 类型 foreign key (列名) references 另一个表名(关联的列名));
create table class (classId int primary key auto_increment,name varchar(20));
create table student (studentId int primary key auto_increment,name varchar(20),classId int,
     foreign key (classId) references class(classId));
desc student;

insert image description here

Since it is a student, there must be a class before the student can enter the class, and the student cannot enter a class that does not exist.

insert into class (null,'高三1班');
insert into class values (null,'高三2班');
insert into class values (null,'高三3班');
insert into student values (null,'张三',1);
insert into student values (null,'李四',4);

insert image description here
insert image description here

Remove foreign key constraints

When the inserted data is not included in the column corresponding to the foreign key, an error will be reported. And in the above foreign key relationship, class is the parent table, student is the child table, the insertion and deletion of the child table are constrained by the parent table, and the deletion of the parent table is also constrained by the child table.

update student set classId = 5;
delete from class where classId = 1;

insert image description here
For the modification of the child table, the modified data of the corresponding column still needs to exist in the parent table. When the parent table is deleted, if the child table is associated with it, then it cannot be deleted. You can only delete the corresponding rows of the child table first, and then delete the parent table.

Guess you like

Origin blog.csdn.net/m0_73888323/article/details/131899843