← 返回首页
MySQL基础教程(十三)
发表时间:2020-03-17 12:23:21
讲解MySQL的约束

约束:所谓约束(constraint),一种限制,用于限制表中的数据,为了保证表中数据的准确性和可靠性。

MySQL有六大约束:

1.NOT NULL :非空,用于保证该字段的值不能为空。例如学生表的学生姓名及学号等等。

2.DEFAULT:默认值,用于保证该字段有默认值。例如学生表的学生性别。

3.PRIMARY KEY:主键,用于保证该字段的值具有唯一性并且非空。例如学生表的学生学号等。

4.UNIQUE:唯一,用于保证该字段的值具有唯一性,可以为空。例如注册用户的手机号,身份证号等。

5.CHECK: 检查约束。用于保证字段值的合法性。

6.FOREIGN KEY:外键,用于限制两个表的关系,用于保证该字段的值必须来自于主表的关联列的值,在从表添加外键约束,用于引用主表中某些的值。例如学生表的专业编号。

1.主键约束

表设计时一定要有主键,如果没有,表示该表无效,因为不能保证数据的完整性(实体的完整性)。 主键又分为单一主键和复合主键(联合主键)。 单一主键:给一个字段添加主键约束 复合主键:给多个字段联合添加一个主键约束(只能用表级定义)

实例:

#单一主键
create table users(
   uid int not null primary key, /*定义单一主键*/
   username varchar(20),
   password varchar(20)  
);

#复合主键
create table users(
   uid int not null unique,
   username varchar(20) not null unique,
   password varchar(20),
   primary key(uid,username)  /*设置联合主键*/
)

2.唯一约束

unique约束的字段,具有唯一性,不可重复,但可以为null。 实例:

create table users(
  uid int not null auto_increment primary key,
  username varchar(20) unique,  /*用户名必须唯一,但是可以为null*/
  password varchar(20) not null
);

唯一约束与主键的区别:

++主键约束 PRIMARY KRY++ - PRIMARY KRY 主键 是唯一的 一张表只能有一个主键 - AUTO_INCREMENT 一定要和主键连用 - 但主键不一定要和 AUTO_INCREMENT 连用 - 主键一定是非空的 NOT NULL

++唯一约束 UNIQUE KEY++ - UNIQUE KEY 唯一约束 - 唯一约束可以保证数据的唯一性 - 唯一约束的字段可以为空 - 每张数据表可以有存在多个唯一约束

3.非空约束

create table users(
  uid int not null auto_increment primary key,
  username varchar(20) unique,
  password varchar(20) not null  /*密码不能为空*/
);

4.默认约束

用于保证该字段有默认值。

create table users(
   uid int not null auto_increment primary key,
   username varchar(20) not null unique,
   password varchar(20) not null,
   birthday datetime default CURRENT_TIMESTAMP  /*设置生日的默认值为当前时间*/
);

insert into users (username,password) values ('admin','admin');
select * from users;

5.检查约束 用于保证字段值的合法性,比如:性别只能是'男'或者'女',年龄大于0小于300.

create table students (
         sid int auto_increment primary key,
     sname varchar(50) not null,
     gender varchar(2) default '男',
     age int not null,
     check (gender='男' or gender='女'),
     check (age >0 and age< 300) 
);

6.外键约束

#学生表
create table students(
   sid int not null auto_increment primary key,
   sname varchar(20) 
);

#课程表
create table course(
   cid varchar(4) not null primary key,
   cname varchar(20)
);

#学生成绩表
create table score(
   sid int not null,
   cid varchar(4) not null,
   score int ,
   foreign key(sid) REFERENCES students (sid), /*sid是外键*/
   foreign key(cid) references course (cid),/*cid是外键*/
   primary key(sid,cid)  /*sid+cid是联合主键*/
);