Relate DB id's Mysql

60 Views Asked by At

I would like to know how can I relate 2 id's. One frome users table and another from stats table. The id from users is AI , Primary and I want to relate the other id to this one. I tried Foreign key constraint (INNODB) and it gave me this error #1452 - Cannot add or update a child row: a foreign key constraint fails (game.#sql-3de_34f, CONSTRAINT ?sql?3de_34f_ibfk_1 FOREIGN KEY (id) REFERENCES user (id)) .

Thanks

2

There are 2 best solutions below

0
On

Try this!

SET foreign_key_checks = 0;

Then run query to add your key, and after that...

SET foreign_key_checks = 1;
0
On

You have USER_IDs in your "stats" table that are not in your "users" table.

Delete them if you think they are not useful anymore.

DELETE FROM stats where user_id NOT IN (SELECT user_id from users);

Then, you can create your reference keys.