How to make a NOT IN mysql with 2 tables

Question:

I have 3 person tables, class_materia, Notes, person table has:

+------+--------------+-----------+
| id   |  Nome        |  turma    |
+------+--------------+-----------+
| 1    | Aluno 01     | 1         |
| 2    | Aluno 02     | 2         |

In the class_matter table you have:

+------+--------+---------+
| id   |  turma | materia |
+------+--------+---------+
| 1    |  1     |  1      |
| 2    |  2     |  1      |
| 3    |  2     |  2      |

In the grade table I need to insert the student and the subject linked to the student's class where there is no grade in the table.
In short, it will check if it already has the material for that student, if not, it will add.
If it were with a table, it would be like this:

SELECT PE.id, PE.nome, TM.materia
FROM pessoa PE
LEFT JOIN turma_materia TM ON PE.turma=TM.turma
WHERE TM.materia NOT IN (SELECT nota_materia FROM nota)

Adding: The note table has

+------+----------+-----------+-------+------+-------+------+
| id   |  Aluno   |  Materia  |  UNI  | UNII | UNIII | UNIV |
+------+----------+-----------+-------+------+-------+------+
| 1    |  1       |   1       |  NULL | NULL | NULL  | NULL |

Answer:

Doing it by parts. We first identify student-grade pairs that do not exist in the Grade table. There are several ways, here is a possible alternative:

SELECT PE.id, PE.nome, TM.materia
  FROM pessoa PE
 INNER JOIN turma_materia TM
    ON TM.turma = PE.turma
  LEFT JOIN nota NT
    ON NT.Aluno = PE.Id
   AND NT.Materia = TM.Materia
 WHERE TM.ID IS NULL   -- Combinação Aluno/Materia não existe na tabela Nota

The only thing missing is the INSERT in the Note table, which can be done like this:

INSERT INTO Nota(Aluno, Materia)
SELECT PE.id, TM.materia
  FROM pessoa PE
 INNER JOIN turma_materia TM
    ON TM.turma = PE.turma
  LEFT JOIN nota NT
    ON NT.Aluno = PE.Id
   AND NT.Materia = TM.Materia
 WHERE TM.ID IS NULL

As detailed in the comment, only the student and the subject are included in the Note table, the rest assume the table's default value.

Here is the link to SQL Fiddle . In this example, the Note table only has information referring to "Student 01", so the SELECT statement will return all subjects in which "Student 02" enrolled.

Scroll to Top