create table student( id int comment '学号'primary key auto_increment , name varchar(20) comment '姓名'not null , age int comment '年龄'check ( age>0and age <=120 ), sex varchar(5) comment '性别'check ( sex ='男'or sex ='女' ), email varchar(20) comment '邮箱'unique, grade int comment '年级'default1 )comment '学生信息';
其中约束的关键字直接添加在每行字段末尾,auto_increment是自增关键字 2. 表级约束
1 2 3 4 5 6 7 8 9 10 11
create table student( id int comment '学号' , name varchar(20) comment '姓名' , age int comment '年龄' , sex varchar(5) comment '性别' , email varchar(20) comment '邮箱', grade int comment '年级' , constraint p_key1 primary key (id), constraint unique1 unique(email), constraint check1 check( age>0and age <=120 ) )comment '学生信息';
insert into student (id, name, age, sex, email,grade) values (3,'菜狗耗子',-1,'男','1122@hah.com',1);
终端会提示你age不符合条件约束
1
[HY000][3819] Checkconstraint'check1'is violated.
B.1.6 外键约束
用来让两张表的数据之间建立连接,从而保证数据的一致性和完整性
使用背景 现在创建两张表,并添加部分成员,代码和表格如下图
创建表(student1)
1 2 3 4 5 6 7
create table student1( id int comment '学号' , name varchar(20) comment '姓名' , age int comment '年龄' , sex varchar(5) comment '性别' , 所属部门id int )comment '学生信息';
创建表(部门)
1 2 3 4
create table 部门( id int , 所属部门 varchar(20) )comment '学生信息';
create table student( id int comment '学号' primary key auto_increment , name varchar(20) comment '姓名' not null , age int comment '年龄' check ( age>0 and age <=120 ), sex varchar(5) comment '性别' check ( sex = '男' or sex = '女' ), email varchar(20) comment '邮箱' unique, grade int comment '年级' default 1 )comment '学生信息';