How to make Foreign key one-to-many in mysql?

Asked

Viewed 991 times

0

I have a table students and a table courses, my table courses have the course for example of administration, as I relate several students to this table using Foreign key ?

  • I don’t have much experience in sql, but usually a third table is created... ex: aluno_curso, where a student can enroll in more than one course and a course can have several students enrolled. This table would have basically an id, idaluno, idcurso. I would do this way.

1 answer

1


First you create the COURSES Table with the column ID_CURSOS (PRIMARY_KEY), then you create a STUDENTS table with the column ID_ALUNOS (primary_key) and the column ID_CURSO. This column ID_CURSO you point to as FOREGN_KEY having as reference the table COURSES, column ID_CURSOS. Following example:

CREATE TABLE `database`.`cursos` (
  `id_cursos` INT NOT NULL AUTO_INCREMENT,
  `nome_curso` VARCHAR(45) NULL,
  PRIMARY KEY (`id_cursos`));


CREATE TABLE `database`.`alunos` (
  `id_alunos` INT NOT NULL AUTO_INCREMENT,
  `id_curso` INT NULL,
  `nome_aluno` VARCHAR(45) NULL,
  PRIMARY KEY (`id_alunos`),
  INDEX `FK_ALUNO_CURSO_idx` (`id_curso` ASC),
  CONSTRAINT `FK_ALUNO_CURSO` 
    FOREIGN KEY (`id_curso`) 
    REFERENCES `vigilant`.`cursos` (`id_cursos`)
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION);

Any questions just talk. Hugs.

  • I understood, how do I put the curricular units (modules) associated with the course name ? the modules are a list as I would create this module, it would be a table for each module ?

  • I’m sorry, but I don’t understand. Explain what modules are. Are the course subjects? Let me get this straight. Example: Course of Administration (Module I: Matter 1, Matter 2, Matter 3; Module II: Matter 4, Matter 5, Matter 6). That’s it?

  • If it is as I understand it, you will have to create a MODULES table and create a FOREGN_KEY referencing to the ID_CURSO of the COURSES table. That is, through this, you will be linking modules to each course.

  • DB relationships are made through Fks. You have relationship 1 to 1 (1:1); 1 to N (1:N); and N to N (N:N). That is, relationship 1:1 is when one table is related to another, but each record points only to another table; 1:N is when a record of one table relates to several other tables; and N:N is when multiple records of one table relate to several records of another table. The latter, to be implemented, must create a third table to create the relationship of several to several. Example is what is in the above answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.