I had a row already in the 'lowlevel' table where the user did not exist. Makes sense now because that is one of the purposes of doing this.
innodb and foreign keys - foreign key constraint fails
-
16-07-2023 - |
문제
I am playing around with a copied db that I have switched to innodb to get a grasp on foreign keys. I have the following tables with their columns underneath. On each fk I am setting ON DELETE : cascade and ON UPDATE : cascade. This works until I get to the 'lowlevel' table where I get :
ALTER TABLE
1452 - Cannot add or update a child row: a foreign key constraint fails (lowlevel
ADD FOREIGN KEY (user_id
) REFERENCEStestdb
.users
(user_id
) ON DELETE CASCADE ON UPDATE CASCADE;testdb
.'#sql-11e6_47710b'>, CONSTRAINT
#sql-11e6_47710b_ibfk_1
FOREIGN KEY (user_id
) REFERENCESusers
(user_id
) ON DELETE CASCADE ON )
The idea is/was should I delete an account from accounts
it would cycle through its computer_id's... its user_id's... then finally its lowlevel rows so the entire user account is removed with one call. On the flip side, it would work backwards and prevent any inserts through this chain if the previous constraint was not set.
I am not running any queries on this... just trying to set the fk's through phpmyadmin right now. Where is my logic wrong here and why can't I set the fk on my 'lowlevel' table example?
My tables :
accounts
---------
account_id (primary)computers
---------
computer_id (primary)
account_id (fk to accounts.account_id)users
---------
user_id (primary)
computer_id (fk to computers.computer_id)lowlevel
---------
id (primary)
user_id (fk to users.user_id)
해결책