1 Overview
-
Concept : Limit the data in the table to ensure the correctness, validity and completeness of the data.
-
Classification :
1. Primary key constraint: primary key
2. Non-empty constraint: not null
3. Unique constraint: unique
4. Foreign key constraint: foreign key
2. Non-empty constraints
Non-null constraint : not null, the value of a column cannot be null
- 1. Add constraints when creating a table
CREATE TABLE stu1(
id INT,
NAME VARCHAR(20) NOT NULL -- name为非空
);
- 2. After creating the table, add a non-empty constraint
ALTER TABLE stu MODIFY NAME VARCHAR(20) NOT NULL;
- 3. Remove the non-empty constraint of name
ALTER TABLE stu MODIFY NAME VARCHAR(20);
3. Unique constraint
unique, the value of a column cannot be repeated
- 1. Note:
* The unique constraint can have a NULL value, but only one record can be null - 2. When creating a table, add a unique constraint
CREATE TABLE stu(
id INT,
phone_number VARCHAR(20) UNIQUE -- 手机号
);
- 3. Remove the unique constraint
ALTER TABLE stu DROP INDEX phone_number;
- 4. After the table is created, add a unique constraint
ALTER TABLE stu MODIFY phone_number VARCHAR(20) UNIQUE;
4. Primary key constraint: primary key
-
1. Note:
1. 含义:非空且唯一 2. 一张表只能有一个字段为主键 3. 主键就是表中记录的唯一标识
-
2. When creating a table, add a primary key constraint
create table stu(
id int primary key,-- 给id添加主键约束
name varchar(20)
);
- 3. Delete the primary key
-- 错误 alter table stu modify id int ;
ALTER TABLE stu DROP PRIMARY KEY;
- 4. After creating the table, add the primary key
ALTER TABLE stu MODIFY id INT PRIMARY KEY;
- 5. Automatic growth:
-
Concept: If a column is of numeric type, use auto_increment to complete the value of automatic growth
-
When creating a table, add primary key constraints and complete primary key self-growth
create table stu(
id int primary key auto_increment,-- 给id添加主键约束
name varchar(20)
);
- 3. Delete automatic growth
ALTER TABLE stu MODIFY id INT;
- 4. Add automatic growth
ALTER TABLE stu MODIFY id INT AUTO_INCREMENT;
5. Foreign key constraints
Foreign key constraint : foreign key, let the table and the table have a relationship, so as to ensure the correctness of the data.
- 1. When creating a table, you can add foreign keys
Syntax:
create table 表名(
....
外键列
constraint 外键名称 foreign key (外键列名称)
references 主表名称(主表列名称)
);
- 2. Delete foreign keys
ALTER TABLE 表名 DROP FOREIGN KEY 外键名称;
- 3. After creating the table, add the foreign key
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY
(外键字段名称) REFERENCES 主表名称(主表列名称);
- 4. Cascade operation
1. Add cascade operation
语法:ALTER TABLE 表名 ADD CONSTRAINT 外键名称
FOREIGN KEY (外键字段名称) REFERENCES 主表名称(主表列名称)
ON UPDATE CASCADE ON DELETE CASCADE ;
-
classification:
1. 级联更新:ON UPDATE CASCADE 2. 级联删除:ON DELETE CASCADE