一对多/多对多 SQL [英] One to Many/many to many SQL
问题描述
我正在使用 mysql 并且遇到了一些困惑.我创建了两个表 academy
和 courses
.我需要帮助来确定如何构建表字段.例如 one to many
模式.一个学院可以提供多门课程,一门课程可以与许多学院一起提供.下表的结构是否正确?
I am working with mysql and running into a little confusion. I have created two tables academy
and courses
. I am needing help in determining how to structure the table fields. For example the one to many
schema. One academy can offer many courses and a course can be offered with many academies. Is the structure for the tables below correct?
create table academy
(
academy_id int(11) not null auto_increment,
course_id int() NOT NULL ,
name varchar(25) not null,
primary key (id),
);
CREATE TABLE course
(
course_id int(11) not null auto_increment,
course_name VARCHAR(50) NOT NULL ,
primary key (course_id),
foreign key (academy_id) REFERENCES academy (academy_id) on delete cascade
);
期望结果示例
id Name Course
1 The Alamo School 125 Intro to Programming
2 Bearcat High School 125 Intro to Programming
推荐答案
您真正需要的是一个用于学院的表、一个用于课程的表以及一个可以存储多对多关系的关系表.我将查询留给您以获取您正在寻找的结果:)
What you really need is a table for the academies, one for the courses and a relationship table where you can store the many-to-many relationships. I leave to you the query to get the result you are looking for :)
CREATE TABLE academy
(
academy_id int(11) not null auto_increment,
name varchar(25) not null,
primary key (id),
);
CREATE TABLE course
(
course_id int(11) not null auto_increment,
course_name VARCHAR(50) NOT NULL ,
primary key (course_id),
);
CREATE TABLE accademy_course
(
academy_id int(11) not null,
course_id int(11) not null ,
primary key (academy_id, course_id),
foreign key (academy_id) REFERENCES academy (academy_id) on delete cascade,
foreign key (course_id) REFERENCES course (course_id) on delete cascade
);
这篇关于一对多/多对多 SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!