【问题标题】:One to Many/many to many SQL一对多/多对多 SQL
【发布时间】:2013-11-09 01:15:55
【问题描述】:

我正在使用 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 

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

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

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

    【讨论】:

    • 现在说得通了。我需要第三张表来创建多对多关系。如果我有教师参与,这是否适用?
    猜你喜欢
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多