foreign_key_checks

Mattepuffo's logo
Usare TRUNCATE TABLE con le Foreing Key

Usare TRUNCATE TABLE con le Foreing Key

L'istruzione TRUNCATE TABLE di MySQL serve per svuotare le tabelle ed azzerare eventuali inidici.

Il problema è che nel caso in cui due tabelle siano collegate tramite foreign key questa istruzione da errore.

Ad esempio io ho una tabella pacchetti e una tabella articoli che ha un FK verso pacchetti.

Se provo a svuotare pacchetti:

mysql> TRUNCATE pacchetti;

ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint (`compagnia`.`articoli`, CONSTRAINT `pacchetto_codice_FK` FOREIGN KEY (`pacchetto_codice`) REFERENCES `compagnia`.`pacchetti` (`pacchetto_codice`))

Si potrebbe usare DELETE, ma non azzera gli indici.

Come fare?