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

ycggw6v2  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(427)

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

  1. CREATE TABLE analytics (
  2. id INT NOT NULL,
  3. status BOOLEAN,
  4. server_id INT, /* link with server info*/
  5. source_id INT, /*link with input source*/
  6. ext VARCHAR(5),
  7. startframe_id_x INT,
  8. endframe_id_x INT,
  9. mask VARCHAR(20),
  10. label VARCHAR(20),
  11. countline INT,
  12. det_deviceid INT,
  13. processing_period TIME,
  14. PRIMARY KEY(id),
  15. FOREIGN KEY (server_id) REFERENCES server_info(id),
  16. FOREIGN KEY (source_id) REFERENCES input_source(id)
  17. );
  18. CREATE TABLE statistics (
  19. id INT NOT NULL,
  20. source_id INT, /*link with input source*/
  21. analytic_id INT, /*link with analytic*/
  22. time_recorded TIMESTAMP,
  23. duration TIME, /*link with analytics processing period*/
  24. counter INT,
  25. PRIMARY KEY (id),
  26. FOREIGN KEY (source_id) REFERENCES input_source(id),
  27. FOREIGN KEY (analytic_id) REFERENCES analytics(id),
  28. FOREIGN KEY (duration) REFERENCES analytics(processing_period)
  29. );

问题发生在这条线上

  1. 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数据库。
希望能有一些解释或解决办法。

8wigbo56

8wigbo561#

您的第二张table应该如下所示:

  1. CREATE TABLE statistics (
  2. id INT NOT NULL,
  3. source_id INT, /*link with input source*/
  4. analytic_id INT, /*link with analytic*/
  5. time_recorded TIMESTAMP,
  6. counter INT,
  7. PRIMARY KEY (id),
  8. FOREIGN KEY (source_id) REFERENCES input_source(id),
  9. FOREIGN KEY (analytic_id) REFERENCES analytics(id)
  10. );

请注意 duration 已删除。如果需要处理周期,则使用 JOIN 与…相匹配 analytics table。

相关问题