简体   繁体   中英

One to Many/many to many SQL

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

Example of desired result

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM