(errno: 150 "The external key constraint is malformed") - mysql

Does anyone know why I am getting the following error message?

errno: 150 "Foreign key constraint is malformed"

CREATE TABLE meter (
    `code` CHAR(5) NOT NULL,
    `type` VARCHAR(30) NOT NULL,
    description VARCHAR(30) NULL,
    location_code CHAR(3) NOT NULL,
CONSTRAINT pri_meter 
    PRIMARY KEY (`code`),
CONSTRAINT for_meter
    FOREIGN KEY (location_code) REFERENCES location (`code`));

CREATE TABLE location(
    `code` CHAR(3) NOT NULL,
    company VARCHAR(30),
    `type` VARCHAR(30),
CONSTRAINT pri_location 
    PRIMARY KEY (`code`));

CREATE TABLE reading(
    meter_code CHAR(5) NOT NULL,
    `when` DATETIME NOT NULL,
    display DECIMAL(9,3) NOT NULL,
    estimate BIT NOT NULL,
CONSTRAINT pri_reading 
    PRIMARY KEY (`when`, meter_code),
CONSTRAINT for_reading
    FOREIGN KEY (meter_code) REFERENCES meter (`code`));

CREATE INDEX index_meter ON meter (location_code);
CREATE INDEX index_reading ON reading (meter_code);
+4
source share
2 answers

First create a table location.

You cannot reference a table column when a table reference has not yet been specified.

In your example, you have a link to the table locationwhen creating the table meter.

+3
source

Before creating a table, Foreign Keyyou must:

1. Create the Primary Key table first.
2. Must better to create all tables first without any Primary Key or Foreign Key Constraints.(Optional)
3. After that, create the Primary key and the Foreign Key Constraints of it.

It's just an idea

0
source

Source: https://habr.com/ru/post/1683197/


All Articles