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

问题描述 投票:0回答:1

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

    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数据库。

将不胜感激。

mysql sql primary-key popsql
1个回答
0
投票

您的第二张表应如下所示:

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匹配analytics表。

© www.soinside.com 2019 - 2024. All rights reserved.