MySQL (mariadb Ver 15.1 Distrib 10.1.44-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2) gave me this error:
ERROR 1005 (HY000) at line 129: Can't create table `Houdini`.`stamp` (errno: 150 "Foreign key constraint is incorrectly formed")
when trying to create this table:
DROP TABLE IF EXISTS stamp;
CREATE TABLE stamp (
id INT NOT NULL,
name VARCHAR(50) NOT NULL,
group_id SMALLINT NOT NULL,
member BOOLEAN NOT NULL DEFAULT FALSE,
rank SMALLINT NOT NULL DEFAULT 1,
description VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY(id),
CONSTRAINT stamp_ibfk_1 FOREIGN KEY (group_id) REFERENCES stamp_group (id) ON DELETE CASCADE ON UPDATE CASCADE
);
What is the correct foreign key constraint for this? I presume group_id
can’t be used for some reason
2
Answers
could be the data type between the two key are not the same
if you use int for id you should use int for group_id
The foreign keys are members of the primary key of the
quest_award_item
table, so they must be the same data type as themselves, but that’s not the problem.You seem to think that they must have the same data type as the primary key of their own table, but this is in fact not required.
The requirement is that foreign key column(s) must have the same data type as the column(s) they reference.
In this case,
quest_award_item.quest_id
must be the same data type asquest.id
.Likewise,
quest_award_item.item_id
must be the same data type asitem.id
.You haven’t shown the table definitions of the
quest
oritem
tables, so we can only guess at their data types. But one or other other may have an incompatible data type.Re your comment:
You posted in a comment below that the
quest.id
column is defined asSERIAL
, which MySQL translates intoBIGINT UNSIGNED AUTO_INCREMENT
.The foreign key column that references
quest.id
must be the same data type as the column it references (the AUTO_INCREMENT part is not necessary to match the data type).So change your CREATE TABLE:
An alternative solution is to modify the
quest.id
to be anINT
, and then your original CREATE TABLE quest_award_item will work.But if you already have rows in that table with id values great enough that they need to be
BIGINT UNSIGNED
(i.e. greater than 231-1), then you can’t do that.