一对多/多对多SQL

时间:2013-11-09 01:15:55

标签: mysql sql

我正在使用mysql并遇到一点混乱。我创建了两个表academycourses。我在确定如何构造表字段时需要帮助。例如one to many架构。一个学院可以提供许多课程,并且可以为许多学院提供课程。下表的结构是否正确?

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 

1 个答案:

答案 0 :(得分:4)

你真正需要的是一个学院的桌子,一个用于课程的桌子和一个你可以存储多对多关系的关系表。我留给您查询以获得您正在寻找的结果:)

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
);