MySQL constraints

Insert picture description here


Preface

1. What are the constraints of MySQL?

1. Not null — Indicates that a column cannot store NULL values.
2. UNIQUE - to ensure that each row of a column must have a unique value.
3. default — specify the default value when no value is assigned to the column.
4. Primary key (primary key )-is a combination of not null and unique. Ensure that a column (or a combination of two columns and multiple columns) has a unique identifier, which helps to find a specific record in the table more easily and quickly.
5. foreign key (foreign key)-to ensure that the data in one table matches the referential integrity of the value in another table.
6. check — to ensure that the values ​​in the column meet the specified conditions. For MySQL databases, the check clause is analyzed, but the check clause is ignored.

2. Examples of constraints

1.NOT NULL

Insert picture description here

2.UNIQUE

When specifying the sn column in the student table, it is unique and not repeatedInsert picture description here

3.DEFAULT

When you specify to insert data, the name
column is empty, and the default value is unkown: there is a default value. It is also possible to insert a null for this field, and the default value will not be used.
Insert picture description here

4.PRIMARY KEY

Specify the id column as the primary key:
Insert picture description here
For the primary key of integer type, it is often used with auto_increment. When the corresponding field of the inserted data does not give a value, the maximum value +1 is used.
Insert picture description here

5.FOREIGN KEY

Foreign keys are used to associate the primary key or unique key of other tables. Syntax:
Insert picture description here
When creating a class table, when MySQL keywords are used as fields, you need to use the '' symbol to identify;
Insert picture description here

Create student table student, one student corresponds to one class, one class corresponds to multiple students, and the relationship between class and student is 1:n. Use id as the primary key and classes_id as the foreign key to associate the class table id;
Insert picture description here

6.CHECK

No error is reported when MySQL is used, but the constraint is ignored:
Insert picture description here


Guess you like

Origin blog.csdn.net/m0_46551861/article/details/109565132