Shikhar Srivastava
Shikhar Srivastava

Reputation: 149

#1215 - Cannot add foreign key constraint in my sql tables

I have 3 tables in which user_id is defined as primary key user_id in table named users and in another table named updates I'm declaring a foreign key references to user_id,this is my users table:

 CREATE TABLE `users` (
`user_id` INT(11) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(45) ,
`password` VARCHAR(100) ,
`email` VARCHAR(45) ,
`friend_count` INT(11) ,
`profile_pic` VARCHAR(150),
PRIMARY KEY (`user_id`));

My update table is:

CREATE TABLE `updates` (
`update_id` INT(11) AUTO_INCREMENT ,
`update` VARCHAR(45),
`user_id_fk` VARCHAR(45),
`created` INT(11) ,
`ip` VARCHAR(45),
PRIMARY KEY (`update_id`),
FOREIGN KEY (user_id_fk) REFERENCES users(user_id));

on adding foreign key it is giving error saying:

#1215 - Cannot add foreign key constraint

so help me out in this?

Upvotes: 0

Views: 73

Answers (1)

Sylvain Martin
Sylvain Martin

Reputation: 2375

You should have users.user_id with the same type and length of updates.user_id_fk :

CREATE TABLE `updates` (
`update_id` INT(11) AUTO_INCREMENT ,
`update` VARCHAR(45),
`user_id_fk` INT(11),
`created` INT(11) ,
`ip` VARCHAR(45),
PRIMARY KEY (`update_id`),
FOREIGN KEY (user_id_fk) REFERENCES users(user_id));

Upvotes: 2

Related Questions