简体   繁体   中英

Adding record to Table (foreign key constraint fails)

I have problem with adding some records to my table (grupy, login(VARCHAR 32, Primary Key, Unique), grupa(VARCHAR 10).

When I try this script:

ALTER TABLE `grupy` ENGINE = InnoDB;

ALTER TABLE `grupy` ADD FOREIGN KEY ( `login` ) REFERENCES `issi`.`pracownicy` (`login`) ON DELETE CASCADE;


INSERT INTO `grupy` (`login`, `grupa`) VALUES
('administrator', 'zalogowany');

I got a error:

Error code 1452, SQL state 23000: Cannot add or update a child row: a foreign key constraint fails ( issi . grupy , CONSTRAINT grupy_ibfk_1 FOREIGN KEY ( login ) REFERENCES pracownicy ( login ) ON DELETE CASCADE) Line 6, column 1

What did I do wrong?

I believe this happens when an existing value is invalid -- ie not in the table. You can check for invalid values easily enough:

select g.*
from grupy g
where not exists (select 1 from issi.pracownicy p on p.login = g.login);

If this is the case, change the existing values (say, to NULL ) and then add the constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM