);
1.4、DEFAULT:默认值约束
指定插入数据时,name列为空,默认值unkown:
drop table if exists student;
create table student(
id int not NULL,
sn int unique,
name varchar(20) default ‘unkown’,
qq_mail varchar(10)
);
1.5、PRIMARY KEY:主键约束
指定id列为主键:
drop table if exists student;
create table student(
id int not NULL primary key,
sn int unique,
name varchar(20) default ‘unkown’,
qq_mail varchar(10)
);
对于整数类型的主键,常配搭自增长auto_increment来使用。插入数据对应字段不给值时,使用最大 值+1。
– 主键是 NOT NULL 和 UNIQUE 的结合,可以不用 NOT NULL
id int primary key auto_increment,
1.6、FOREIGN KEY:外键约束
外键用于关联其他表的主键或唯一键,语法:
foreign key (字段名) references 主表(列)
创建班级表classes,id为主键:
– 创建班级表,有使用MySQL关键字作为字段时,需要使用``来标识
drop table if exists classes;
create table classes(
id int primary key auto_increment,
name varchar(20),
desc
varchar(100)
);
创建学生表student,一个学生对应一个班级,一个班级对应多个学生。使用id为主键, classes_id为外键,关联班级表id
drop table if exists student;
create table student(
id int primary key auto_increment,
sn int unique,
name varchar(20) default ‘unkown’,
qq_mail varchar(20),
classes_id int,
foreign key (classes_id) references classes(id)
);
1.7、CHECK约束(了解)
MySQL使用时不报错,但忽略该约束:
drop table if exists test_user;
create table test_user(
id int,
name varchar(20),
sex varchar(1),
check(sex = ‘男’ or sex = ‘女’)
);
二、表的设计
==========
2.1、三大范式
一对一
一对多
多对多
创建课程表
drop table if exists test_user;
create ta