Reputation: 121
I am getting an error while running the following commands on a MySQL server.
CREATE TABLE users (
userID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(userID),
firstname VARCHAR(100) NOT NULL,
lastname VARCHAR(100) NOT NULL,
username VARCHAR(120) NOT NULL UNIQUE,
hashpass VARCHAR(100) NOT NULL
) ENGINE=INNODB ;
CREATE TABLE posts (
postID INT AUTO_INCREMENT,
text VARCHAR(1000),
imageURI VARCHAR(100),
userID VARCHAR(120) NOT NULL,
PRIMARY KEY(postID),
FOREIGN KEY (userID)
REFERENCES users (userID)
ON DELETE CASCADE,
tags VARCHAR(500)
) ENGINE=INNODB;
I am getting the following error:
Cannot add foreign key constraint
Upvotes: 1
Views: 62
Reputation: 172448
Try to use the same type of your primary keys - users.userID int
- on the foreign keys - posts.userID
- as well.
Try like this:
CREATE TABLE users (
userID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(userID),
firstname VARCHAR(100) NOT NULL,
lastname VARCHAR(100) NOT NULL,
username VARCHAR(120) NOT NULL UNIQUE,
hashpass VARCHAR(100) NOT NULL
) ENGINE=INNODB ;
CREATE TABLE posts (
postID INT AUTO_INCREMENT,
text VARCHAR(1000),
imageURI VARCHAR(100),
userID INT NOT NULL, <---Change here
PRIMARY KEY(postID),
FOREIGN KEY (userID)
REFERENCES users (userID)
ON DELETE CASCADE,
tags VARCHAR(500)
) ENGINE=INNODB;
Upvotes: 1
Reputation: 765
your foreign key
userID VARCHAR(120) NOT NULL,
is different with
userID INT NOT NULL AUTO_INCREMENT,
Upvotes: 0