Gdy MySQL wymądrza się
marzec 30th, 2008Dziś trafiłem na dziwne zachowanie MySQL, próbował zabezpieczyć się przed moimi działaniami na wszystkie sposoby
Są dwa pliki z kodem SQL, jeden czysty ‘create’ a drugi to ‘insert’, musiałem rozszerzyć nieco pewne tabele o klucze obce ale nie chciało mi się zmieniać porządku tworzenia ich więc dodałem wymagane kolumny aby potem za pomocą ALTER TABLE dodać klucze obce.
Niespodzianka
ALTER TABLE messages_customer ADD CONSTRAINT messages_customer_key2 FOREIGN KEY (customer_id) REFERENCES user_accounts(id) ON DELETE CASCADE ON UPDATE CASCADE;
ERROR 1452 (23000) at line 778: Cannot add or update a child row: a foreign key constraint fails (`adnet_full/#sql-40d6_d2d8`, CONSTRAINT `messages_customer_key2` FOREIGN KEY (`customer_id`) REFERENCES `user_accounts` (`id`))
Ponieważ w żadnej z tabel nie ma jeszcze danych. Okazuje się, że trzeba “przytępić” nieco wbudowane triggery mysql czyli
SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE messages_customer ADD CONSTRAINT messages_customer_key2 FOREIGN KEY (customer_id) REFERENCES user_accounts(id) ON DELETE CASCADE ON UPDATE CASCADE;
SET FOREIGN_KEY_CHECKS=1;
I już da się rozszerzyć tabelę.
kwiecień 3rd, 2008 at 4:53 am
does anyone knows if there is any other information about this subject in other languages?
kwiecień 3rd, 2008 at 7:24 am
I can descibe problem in english if you wish
When you alter table adding foreign key MYSQL by default checks if in reference table are records, if not then you’ll see this error. To awoid this before alter operation you must set ‘foreign_key_check=0′, then alter table (can be empty table) and then back set ’set foreign_key_checks=1′