MySQL Errno:150"外键约束形成错误"

时间:2017-08-07 22:46:48

标签: mysql

有谁知道为什么我收到以下错误消息?

  

错误:150"外键约束形成错误"

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);

2 个答案:

答案 0 :(得分:4)

首先创建location表。

当引用的表尚不存在时,您无法引用表列。

在您的示例中,您在创建location表时引用了表meter

答案 1 :(得分:0)

在创建Foreign Key表之前,您必须:

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.

这只是一个想法