Reputation: 2019
I have a SQL script that yields me the error:
DROP TABLE IF EXISTS test_db.users
;
CREATE TABLE users
(
id SERIAL,
username VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL,
PRIMARY KEY (id)
);
DROP TABLE IF EXISTS test_db.comments
;
CREATE TABLE comments
(
id SERIAL,
content varchar(255) NOT NULL,
userId BIGINT(20) NOT NULL,
CONSTRAINT fk_comments_has_user
FOREIGN KEY (userId)
REFERENCES test_db.users(id)
ON DELETE CASCADE,
PRIMARY KEY (id)
);
ERROR 1215 (HY000): Cannot add foreign key constraint
This error is not so specific, and I can't really seem to pinpoint the error by reading other posts regarding similar error.
Upvotes: 1
Views: 27
Reputation: 17655
The datatypes need to be the same bigint is not the same as serial. Try this
drop table if exists comments;
DROP TABLE IF EXISTS temp;
CREATE TABLE temp
(
id bigint auto_increment,
username VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL,
PRIMARY KEY (id)
);
DROP TABLE IF EXISTS comments
;
CREATE TABLE comments
(
id bigint auto_increment,
content varchar(255) NOT NULL,
userId bigint NOT NULL,
CONSTRAINT fk_comments_has_user
FOREIGN KEY (userId)
REFERENCES temp(id)
ON DELETE CASCADE,
PRIMARY KEY (id)
);
Upvotes: 2