Why I cannot assign foreign key to this column?

2019-09-18 07:15发布

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?

2条回答
女痞
2楼-- · 2019-09-18 07:20

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

查看更多
forever°为你锁心
3楼-- · 2019-09-18 07:40

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

查看更多
登录 后发表回答