【发布时间】:2020-06-03 09:34:33
【问题描述】:
过去两天我自己才开始学习 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 数据库。
希望得到一些解释或解决方案。
【问题讨论】:
-
错误出现在 FOREIGN KEY (duration) REFERENCES analytics(processing_period) 上,是因为 processing_period 上没有索引。
-
有什么办法可以解决这个问题吗? @P.鲑鱼
-
'在 processing_period 上没有索引' - 解决这个问题的方法是添加一个索引 - 如果你不能这样做,那么你就不能有一个 FK,你可能必须使用触发器来验证持续时间。
-
FOREIGN KEY引用的列(analytics.processing_period)必须根据索引定义为UNIQUE。
-
@Akina 据我了解,我需要将 analytics.processing_period 更改为唯一数据类型?对吗?
标签: mysql sql primary-key popsql