mysql - 我怎样才能解决外键没有索引父?
问题描述
在过去的两天里,我自己才开始学习 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 数据库。
将不胜感激一些解释或解决方案。
解决方案
您的第二个表应如下所示:
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
表。
推荐阅读
- python - python setup.py 的编译器选项
- php - 获取base64编码字符串的文件扩展名
- javascript - 使用 vue.js 将格式价格更改为印尼盾
- sql - SQL Server:获取子字符串(名字,姓氏,姓氏)
- pandas - Pandas / Plot.plt 折线图,水平 X 值
- javascript - Dropzonejs 和 Node/Multer 照片上传未显示在服务器上。
- android - RemoteViews ListView setScrollPosition 未命中
- python - 如何在 Django 中对模型的所有实例求和
- javascript - 使用 multer 传递 memoryStorage 以用 ajax 表示但 req.file 未定义
- batch-file - 批处理文件 - 主机文件编辑器 - 防止重复条目 - 删除以前添加的条目