我如何解决外键没有索引父项?

How can i solve foreign key no index parent?

我在过去 2 天才开始学习 SQL,现在我遇到了使用外键约束在不同 table 上链接列的问题。 下面是我的代码。

    CREATE TABLE analytics (
    id INT NOT NULL,
    status BOOLEAN,
    server_id INT,  /* link with server info*/     
    source_id INT,      /*link with input source*/
    ext VARCHAR(5),
    startframe_id_x INT,
    endframe_id_x INT,
    mask VARCHAR(20),
    label VARCHAR(20),
    countline INT,
    det_deviceid INT,
    processing_period TIME,
    PRIMARY KEY(id),
    FOREIGN KEY (server_id) REFERENCES server_info(id),
    FOREIGN KEY (source_id) REFERENCES input_source(id)
);


CREATE TABLE statistics (
    id INT NOT NULL,
    source_id INT,  /*link with input source*/
    analytic_id INT, /*link with analytic*/
    time_recorded TIMESTAMP,
    duration TIME,   /*link with analytics processing period*/
    counter INT,
    PRIMARY KEY (id),
    FOREIGN KEY (source_id) REFERENCES input_source(id),
    FOREIGN KEY (analytic_id) REFERENCES analytics(id),
    FOREIGN KEY (duration) REFERENCES analytics(processing_period)
);

问题出现在这一行

   FOREIGN KEY (duration) REFERENCES analytics(processing_period)

我不确定并用了无数小时搜索和找出解决方案但仍然无法修复它。

它给出了这样的错误"ER_FK_INDEX_PARENT: Failed to add the foreign key constraint. Missing index for constraint 'statistics_ibfk_3' in the referenced table 'analytics'"

谁能说出为什么会出现这个问题?我正在使用 Popsql 编辑我的代码并使用 mysql 数据库。

希望得到一些解释或解决方案。

你的第二个 table 应该是这样的:

CREATE TABLE statistics (
    id INT NOT NULL,
    source_id INT,  /*link with input source*/
    analytic_id INT, /*link with analytic*/
    time_recorded TIMESTAMP,
    counter INT,
    PRIMARY KEY (id),
    FOREIGN KEY (source_id) REFERENCES input_source(id),
    FOREIGN KEY (analytic_id) REFERENCES analytics(id)
);

请注意,duration 已被删除。如果要处理周期,那么用JOIN匹配到analyticstable.