多对多:
例如:
一个学生可以学多门课程
一门课程可以有多个学生: 多对多
创建学生表:
create table students(
id int primary key auto_increment,
name varchar(20) not null,
gender char(10)
);
创建课程表:
create table course(
id int primary key auto_increment,
course_name varchar (20) not null
);
创建关系表:
create table std_cou(
id int primary key auto_increment,
sid int,
cid int,
-- 创建外键
CONSTRAINT fk_sid FOREIGN KEY(sid) references students(id),
CONSTRAINT fk_cid FOREIGN KEY(cid) references course(id)
);
一对多:在多的一方 建立外键
例如:
一个班级对应多个学生:
班级表:
create table class(
id int primary key auto_increment,
classnum VARCHAR(20) not null
);
新的学生表:
create table student(
id int primary key auto_increment,
name varchar(20) not null,
gender char(10),
class_id int,
-- 创建外键
CONSTRAINT fk_class FOREIGN key (class_id) REFERENCES class(id)
);
一对一:
例如:
一个老师教一门课
一门课对应一个老师
创建课程表:
create table courses(
id int PRIMARY key ,
cour_name VARCHAR(20) not null
);
创建教室表:
create table teacher(
id int PRIMARY key auto_increment,
tea_num char(11) not null UNIQUE,
age int ,
-- 添加外键 用主键去关联主键
CONSTRAINT fk_cour_tea FOREIGN KEY (id) REFERENCES courses(id)
);