I searched for a solution to this problem on the Internet and checked the Stack Overflow questions, but none of the solutions worked for my case.
I want to create a foreign key from table sira_no to metal_kod.
ALTER TABLE sira_no
ADD CONSTRAINT METAL_KODU FOREIGN KEY(METAL_KODU)
REFERENCES metal_kod(METAL_KODU)
ON DELETE SET NULL
ON UPDATE SET NULL ;
This script returns:
Error Code: 1005. Can't create table 'ebs.#sql-f48_1a3' (errno: 150)
I tried adding an index to the referenced table:
CREATE INDEX METAL_KODU_INDEX ON metal_kod (METAL_KODU);
I checked METAL_KODU on both tables (charset and collation), but I couldn't find a solution to this problem. How can I fix this problem?
Here is the metal_kod table:
METAL_KODU varchar(4) NO PRI
DURUM bit(1) NO
METAL_ISMI varchar(30) NO
AYAR_YOGUNLUK smallint(6) YES 100
Error Code: 1005 -- there is a wrong primary key reference in your code
Usually it's due to a referenced foreign key field that does not exist. It might be you have a typo mistake, or check case it should be same, or there's a field-type mismatch. Foreign key-linked fields must match definitions exactly.
Some known causes may be:
INT(10)
the key field needs to be INT(10)
as well and not INT(11)
or TINYINT
. You may want to confirm the field size using SHOW
CREATE
TABLE
because Query Browser will sometimes visually show just INTEGER
for both INT(10)
and INT(11)
. You should also check that one is not SIGNED
and the other is UNSIGNED
. They both need to be exactly the same.MyISAM
table. In order to use foreign keys, the tables must both be InnoDB
. (Actually, if both tables are MyISAM
then you won’t get an error message - it just won’t create the key.) In Query Browser, you can specify the table type.ON
DELETE
SET
NULL
, but the relevant key field is set to NOT
NULL
. You can fix this by either changing your cascade or setting the field to allow NULL
values.ALTER
statement or you have mistyped one of the field names in the relationshipFor more details, refer to: MySQL Error Number 1005 Can’t create table