-->

Why I cannot assign foreign key to this column?

2019-09-18 07:21发布

问题:

I've got a main table of users

create table `users` (
`id` int (10),
`first_name` varchar (192),
`last_name` varchar (192),
`password` varchar (96),
`phone` int (10),
`email` varchar (768),
`date_created` timestamp 
); 

then I have a table of accounts, with foreign key user_id referring to main table of users

create table `accounts` (
`id` int (10),
`user_id` int (11),
`account_number` bigint (12),
`account_type` varchar (192),
`balance` double ,
`currency` varchar (9),
`date_created` timestamp 
); 

and at the end, I have a table of transactions, however I'm not able to assign foreign key to user ID as well

create table `transactions` (
`id` int (10),
`user_id` int (11),
`from_account_id` int (12),
`to_account_id` int (11),
`amount` double ,
`currency` varchar (9),
`timestamp` timestamp 
 ); 

Whenever I try to add a foreign key to user_id from transactions table to refer to user_id in accounts, or id in users table I get same error both of the times.

Cannot add or update a child row: a foreign key constraint fails (bank.#sql-34ec_2, CONSTRAINT #sql-34ec_2_ibfk_3 FOREIGN KEY (user_id) REFERENCES accounts (user_id))

How can I avoid that, what else could I do to get the proper referring of particular cells?

回答1:

Truncate the all tables and than set the foreign key for this values.



回答2:

Your data types might be different. 10 versus 11. Show code u are executing