7.5 MySQL Constraint Control

Database Integrity Constraints

(1) Entity integrity

Enforce the integrity of the identifier column or primary key in the table
eg: primary key constraint, unique constraint

(2) Referential Integrity (Referential Integrity)

Referential integrity preserves defined relationships between tables when records are deleted and entered, and referential integrity ensures that key values ​​are consistent across all tables.

(3) User-defined integrity

User-defined business rules, including domain integrity. Including type, format, value range, etc.


Common constraints in MySQL

1. Primary key constraint (PRIMARY KEY)

Used to define the primary key of the basic table, which acts as a unique identifier(不能为NULL,不能重复)

  • Definition for column constraints ([[#1 single primary key|single column as primary key]])
字段名 数据类型 [其它约束] PRIMARY KEY
  • For the definition of table constraints ([[#2 multiple primary keys|multiple columns combined as primary keys]])
PRIMARY KEY (列名[,列名])

(1) Single primary key

[Example 7-18] Create a Stu table and define Sno as the primary key of Stu.

CREATE TABLE Stu
Sno char(6) PRIMARY KEY,
Sname char(8),
Ssex char(2),
Zno varchar(20));

or

CREATE TABLE Stu
Sno char(6) NOT NULL,
Sname char(8),
Ssex char(2),
Zno varchar(20),
PRIMARY KEY(Sno)
);

(2) Multiple primary keys

[Example 7-20] Create an SC table, the primary key is composed of Sno and Cno.

create table sc
sno char(12),
cno char(10) , 
score int,
primary key(sno,cno)
);

(3) Add primary key constraints to existing tables

ALTER TABLE Stu
ADD PRIMARY KEY (Sno);

(4) Delete existing primary key constraints

ALTER TABLE Stu
DROP PRIMARY KEY;

2. Foreign key constraints (FOREIGN KEY)

The foreign key of the child table refers to the primary key of the parent table

[FOREIGN KEY (子表列名表)] REFERENCES 父表名(列名表)
[ on delete [ cascade | restrict | set null | no action ]]
[ on update [ cascade | restrict | set null | no action ]]

cascade: Cascading delete, that is, delete the primary key table and delete the foreign key table at the same time.

If a department in the department table is deleted, if you want to query the information of the department corresponding to the deleted department number in the student table, an error will be reported, because this department no longer exists, so delete the department When connecting a table (primary key table), other tables associated with it must be deleted. This explains the role of foreign keys to maintain data consistency and integrity. Of course, on the other hand, if you delete the records in the student table, it will not affect the data in the department table, and you can query the department number correctly. So deleting the data in the foreign key table does not affect the primary key table.

set null: When the value is Set Null, when deleting the corresponding record in the primary key table, first check whether the record has a corresponding foreign key, and if so, set the foreign key value in the child table to null

no action, restrict: default; means to reject the operation, if the primary key in the parent table is referenced by the child table, when the primary key of the parent table is deleted, the operation will be rejected

The difference between NO ACTION and RESTRICT: only in and individual cases will lead to the difference, the former is executed after the actions of other constraints, and the latter has the highest priority to execute.

Example: Create an SC table, define Sno as a foreign key, and refer to the sno of the S table

CREATE TABLE SC
(Sno char(6)
 Cno char(3),
 Score Int,
PRIMARY KEY (Sno, Cno),
FOREIGN key (Sno) REFERENCES S(Sno)
 )ENGINE=InnoDB;

Note: MyISAM storage engine does not support foreign keys


3. Not null constraint (not null)

注意:NULL不同于0、""、空格、'NULL'

(1) Grammar

属性名 数据类型 [NULL | NOT NULL]

(2) Examples

Create an S table and set the Sname field to be non-empty

CREATE TABLE S
(Sno char(6),
Sname char(8) NOT NULL,
Ssex char(2),
Sbirth date);

(3) Add a non-null constraint to an attribute of an existing table

If you set a non-null constraint on the Sname field in an already created Stu table
and use modify to modify it, you cannot use ADD to increase it

ALTER TABLE S
MODIFY Sname char(8) not null;

4. The only constraint (UNIQUE)

Indicates that the value of a certain column or a combination of multiple columns in the basic table must be unique.
When establishing a UNIQUE constraint, the following factors need to be considered:

  • A table is allowed to have 多个UNIQUE约束.
  • A field that satisfies the UNIQUE constraint 允许取NULL值.
  • UNIQUE constraints can be defined on multiple fields.
  • The UNIQUE constraint automatically creates a unique index on the specified field. If you delete the unique constraint, you can delete the index directly

(1) A single attribute

[Example 7-26] Create a Dept table and define Dname as the only constraint

CREATE TABLE Dept
(Dno char(6)PRIMARY KEY,
 Dname,varchar(20) UNIQUE,
 Tel char(13),
 Address varchar (20)
 );

(2) Multiple attributes

[Example] Create an SC table and define Sno+Cno as the unique key.

CREATE TABLE SC
(Sno char(6),
Cno char(8),
Score int,
UNIQUE (Sno,Cno)
);

(3) The table has already been modified

ALTER TABEL S
MODIFY SNO char(20) NOT NULL UNIQUE;

(4) The difference between PRIMARY KEY and UNIQUE

  • There can only be one PRIMARY KEY in a basic table, but there can be multiple UNIQUE
  • For a column or a combination of multiple columns specified as PRIMARY KEY, none of the columns can have a NULL value, and for the unique key constrained by UNIQUE, NULL is allowed

5. Default constraints (DEFAULT)

Add a default value to a field

(1) Syntax format:

字段名 数据类型 [其它约束] DEFAULT 默认值

(2) Examples

Create a course C table, and set the default value constraint in the up_limit field of the upper limit of the number of course candidates, and the default value is an integer of 100 people.

CREATE TABLE C
(Cno char(8),
 Cname varchar(20),
 up_limit int default 100
);

6. Self-increasing constraints (AUTO_INCREMENT)

  • It is an auto-extended integrity constraint. When a new record is inserted into the table, the value of the field will automatically generate a unique ID.
  • Only one constraint can be created in a table, and it must be 整型.

(1) Grammatical format

列名 数据类型 AUTO_INCREMENT

(2) Examples

Create the department table Dept table, and require the department number to be automatically incremented.

CREATE TABLE Dept1
(Dno INT PRIMARY KEY AUTO_INCREMENT,
 Dname varchar(20) UNIQUE,
 Tel char(13),
 Address varchar (20)
);

这种递增的列必须为主键,AUTO_INCREMENT必须配合PRIMARY KEY


7. You can name constraints (constraint)

(1) Default naming

If it is not named, the system will automatically name the constraint when creating the constraint You
can use the statement to view the commands used to create the table, including constraints

show create table <表名>

(2) Custom naming

[Example 3-12] Create an SC table containing the named constraints.

CREATE TABLE SC1
(Sno char(8),
 Cno char(4),
 Grade INT default 100 null,
 Primary key(sno,cno),
 constraint s_sc_fk
 Foreign key (sno) references Stu(sno)
 ) ;

7. Delete constraints

(1) Delete the primary key

alter table test 
drop primary key;

(2) Delete foreign key constraints

Drop the foreign key constraint named test_ibfk_1

alter table test 
drop foreign key test_ibfk_1;

(3) Delete the unique constraint

alter table tableName 
drop index key_name;

(4) Delete default constraints

ALTER TABLE <数据表名> 
CHANGE COLUMN <字段名> <字段名> <数据类型> DEFAULT NULL;

Guess you like

Origin blog.csdn.net/qq_25887493/article/details/123901488