MySQL创建表与表之间的联系

选课系统

6. 创建数据库创建数据库设置编码为UTF8

CREATE DATABASE choose CHARSET = utf8;

 6.1 创建班级表

表名:classes
字段:
class_no 整型 自增长 主键 -- 班级编号
class_name char(20) 非空   唯一 -- 班级名称
department_name char(20) 非空 -- 院系名称

create table classes(
    class_no int auto_increment primary key,
    class_name char(10) unique not null,
    department_name char(20) not null
  );

6.2 创建教师表

表名:teacher
字段:
teacher_no char(10) 主键 -- 教师工号
teacher_name char(10) 非空 -- 教师姓名
teacher_contact char(20) 非空 -- 联系方式

  create table teacher(
    teacher_no char(10) primary key,
    teacher_name char(10) not null,
    teacher_contact char(20) not null
  );

6.3 创建学生表

表名: student
字段:
student_no char(11) 主键 --学号
student_name char(10) 非空 --姓名
student_contact char(20) 非空 --联系方式
class_no int 外键 --引用的是班级表中的班号(class_no)|学生表和班级表中的外键

  create table student(
     student_no char(11) primary key,
     student_name char(10) not null,
     student_contact char(20) not null,
     class_no int,
设定约束别名(student_class_fk)指定自身字段(class_no)为外键来引用学生表(classes)的字段(class_no)
constraint student_class_fk foreign key(class_no) references classes(class_no) );

6.4 创建课程表

表名: course
字段:
course_no int 自增长 主键 --课程号
course_name char(16) 非空 --课程名
up_limit int 默认 60 --人数上限值
description varchar(100) 非空 --描述信息
status char(6) 默认 未审核 --课程状态默认值(未审核)
teacher_no char(10) 非空 唯一 外键 --主讲老师|课程表和教师表之间的外键

 create table course(
   course_no int auto_increment primary key,
   course_name char(16) not null,
   up_limit int default 60,
   description varchar(100) not null,
   status char(6) default '未审核',
   teacher_no char(10) unique not null,
   constraint course_teacher_fk foreign key(teacher_no) references teacher(teacher_no) 
 ); 

6.5 创建选课表

表名: choose
字段:
choose_no int 自增长 主键 --编号
student_no char(11) 非空 外键 --学生学号
course_no int 非空 外键 --课程号
score tinyint unsigned --成绩
choose_time datetime 非空 --选课时间

 create table choose(
   choose_no int auto_increment primary key,
   student_no char(11) not null,
   course_no int not null,
   choose_time datetime not null,
   score tinyint unsigned,
   constraint choose_student_fk foreign key(student_no) references student(student_no),
   constraint choose_course_fk foreign key(course_no) references course(course_no)
 );

6.6多对多的基本模型基本完成

何所为,不仅仅是一种态度,更是一种艺术!
原文地址:https://www.cnblogs.com/tanzizheng/p/12854345.html