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?
Usiamo questo trucchetto; fate un dump del db per sicurezza e poi usate questa sequenza:
mysql> SET foreign_key_checks = 0;
mysql> TRUNCATE pacchetti;
mysql> TRUNCATE atre_tb;
mysql> SET foreign_key_checks = 1;
In pratica azzeriamo i check sulle FK in modo da poter eseguire l'istruzione TRUNCATE.
Poi reimpostiamo il check.
mysql truncate foreign_key_checks
Commentami!