I would start by creating a UNIQUE key in (asignatura, profesor)
.
Once this is done, you can use INSERT IGNORE
:
INSERT IGNORE INTO joom37_docencia_prof_asig (asignatura,profesor)
VALUES ('asignatura1','profesor1')
That simply skips the insertion if the new record collides with a single tuple. Also, since we are talking about MySQL you can use the convenience method REPLACE instead of INSERT .
REPLACE INTO joom37_docencia_prof_asig (asignatura,profesor)
VALUES ('asignatura1','profesor1')
But this implies that if the key exists, it will delete the existing row and add another one. If there is a self-incremental ID field, it will change the ID because it will be a new row.
Finally, depending on your use case, you could also use INSERT ... ON DUPLICATE , for example if you want the row containing the single tuple not to be modified, but a field that reflects the last update is updated:
INSERT INTO joom37_docencia_prof_asig (asignatura,profesor)
VALUES ('asignatura1','profesor1')
ON DUPLICATE KEY UPDATE actualizacion = now();
In summary, this is a part of the logic that I would prefer to use with the native tools of the DB to protect the integrity of the data.