mysql - 一对多/多对多 SQL

标签 mysql sql

我正在使用 mysql 并遇到了一些困惑。我创建了两个表 academycourses。我需要帮助来确定如何构建表字段。例如 one to many 模式。一个学院可以提供很多类(class),一个类(class)可以与许多学院一起提供。下表的结构是否正确?

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 

最佳答案

您真正需要的是学院表、类(class)表和可以存储多对多关系的关系表。我将查询留给您以获得您正在寻找的结果:)

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

关于mysql - 一对多/多对多 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19871237/

相关文章:

php - 将 CSV 文件转换为 Mysql 数据库 PHP

mysql - 如何将文本格式的日期数据类型更改为日期时间格式

SQL 执行次数最多的查询?

java - Hibernate getNamedQuery执行其他UPDATE TABLE

sql - 在SQL中减去前一行减去当前行

数据库更新的 PHP 查询执行成功但值未在数据库表上更新

java - vaadin 中的数据库表更新

sql - 交易范围和准备好的报表

java - 在实例中运行并在再次运行前停止 5 分钟的代码

php - 这个sql代码有什么问题?