How can I avoid repetition of values in columns in a Mysql table?

0

I've already tried it with UNIQUE and CHECK but it does not work for me.

If there is a teacher with a subject, I would like you not to put the same subject back to me, because the rest of the code I have makes it repeat.

* * *

for($i=0;$i<count($profesores);$i++){
if($profesores[$i]!="")
{
$Query=$link->prepare ("insert into joom37_docencia_prof_asig (asignatura,profesor)  VALUES ('".$asignatura."','".$profesores[$i]."')");
$Query->execute();

}

* *

    
asked by Nicolas Cortizo 22.11.2017 в 18:03
source

1 answer

0

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.

    
answered by 23.11.2017 / 12:28
source