约束
# 约束
在创建表的时候,给表的字段添加约束条件,保证表中数据的完整性和有效性。
# 非空约束 not null
约束的字段不能为 NULL。只允许是列级约束。没有表级约束。
mysql> drop table if exists test;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> create table test(id int,name varchar(255) not null);
Query OK, 0 rows affected (0.01 sec)
1
2
3
4
5
2
3
4
5
# 唯一性约束 unique
mysql> drop table if exists test;
Query OK, 0 rows affected, 1 warning (0.00 sec)
# name 非空 唯一约束
# 约束添加在列后面称为列级约束
mysql> create table test(id int,name varchar(255) not null unique);
Query OK, 0 rows affected (0.01 sec)
# name 和 email 联合唯一约束
# 约束添加在所有列后面别称为表级约束
mysql> create table test(id int,name varchar(255) not null,email varchar(255) not null, unique(name,email));
Query OK, 0 rows affected (0.01 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
需要给多个字段添加某个约束的时候需要使用表级约束。
not null unique 同时使用时在某个字段时,该字段就自动成为了主键字段。
# 主键约束 primary key
主键约束:是一种约束关系。
主键字段:添加了主键约束的字段。
主键值:主键值是每一行记录的唯一标识。
mysql> create table test(id int primary key , name varchar(255) not null);
Query OK, 0 rows affected (0.01 sec)
# auto_increment 自动维护一个主键值
mysql> create table test(id int primary key auto_increent , name varchar(255) not null);
Query OK, 0 rows affected (0.01 sec)
mysql> create table test(id int , name varchar(255) not null , primary key (id));
Query OK, 0 rows affected (0.01 sec)
# 多个字段联合起来做主键,不建议使用复合主键。建议使用单一主键。
mysql> create table test(id int , name varchar(255) not null ,email varchar(255), primary key (id,email));
Query OK, 0 rows affected (0.01 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
一张表 主键约束只能添加一个。主键建议使用 int bigint char等类型。不建议使用 varchar。
主键除了单一主键和复合主键外还有自然主键和业务主键。自然主键就是个数字,不重复就行。业务主键当业务变化时就会影响主键,所以不建议使用业务主键,要多使用自然主键。
# 外键约束 foreign key
外键约束:一种约束条件。
外键字段:外键约束的字段。
外键值:外键字段的值。
mysql> create table t_class(classno int primary key, classname varchar(255));
Query OK, 0 rows affected (0.01 sec)
mysql> create table t_student(studentno int primary key auto_increment,name varchar(255),cno int,foreign key(cno) references t_class(classno));
Query OK, 0 rows affected (0.01 sec)
1
2
3
4
5
2
3
4
5
外键不一定是主键但必须保证是唯一的。
# 检查约束 check constraint
mysql 不支持检查约束。
编辑 (opens new window)
上次更新: 2025/02/10, 20:20:37