I am trying to create a table in MySQL but I get the following error:

Viewed 49

"Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'users_ibfk_1' in the referenced table 'users'"

Here's what I have so far:

DROP TABLE IF EXISTS `books`;
CREATE TABLE `books`(
`title` VARCHAR(50) NOT NULL,
`year` INT,
`edition` VARCHAR(10),
`authorLast` VARCHAR(10),
`authorFirst` VARCHAR(10),
`major` VARCHAR(4),
`courseNo` INT,
`profLast` VARCHAR(10),
`profFirst` VARCHAR(10),
`quality` VARCHAR(10) NOT NULL,
`price` FLOAT NOT NULL,
`user` VARCHAR(10) NOT NULL UNIQUE,
`ISBN` BIGINT NOT NULL,
PRIMARY KEY (`ISBN`)
);

-- Users Table
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users`(
`nameFirst` VARCHAR(10) NOT NULL,
`nameLast` VARCHAR(10),
`user` VARCHAR(10) NOT NULL UNIQUE,
`email` VARCHAR(20) NOT NULL,
`phoneNo` INT,
`major` VARCHAR(10),
`major2` VARCHAR(10),
PRIMARY KEY (`email`),
FOREIGN KEY (`user`) REFERENCES `users` (`user`) ON DELETE CASCADE ON UPDATE CASCADE
);

I've tried making the attributes unique because I read somewhere that that could be the problem but that doesn't seem to be my issue. I'm coming back to MySQL for the first time in a while so this can be a really simple error I'm just not seeing but I would appreciate the help! Thanks.

1 Answers

Your foreign key in the users table is referring same user column in same table

Related