繁体   English   中英

我的MySQL外键约束有什么问题?

[英]What is wrong with my mysql foreign key constraints?

我正在做一个个人项目,这是我一生中第一次真正地尝试建立一个经过规范化的数据库(至少在您进行规范化的第一个级别上)。 这是我的问题涉及的表:

CREATE TABLE `reoccurrences` (
  `name` varchar(15) NOT NULL DEFAULT '',
  `username` varchar(31) NOT NULL DEFAULT '',
  `amount` float(7,2) NOT NULL DEFAULT '0.00',
  `action` varchar(15) NOT NULL DEFAULT '',
  `frequency` varchar(15) NOT NULL DEFAULT '',
  PRIMARY KEY (`name`,`username`),
  KEY `fk_reoccurrences_user` (`username`),
  KEY `fk_reoccurrences_action` (`action`),
  KEY `fk_reoccurrences_frequency` (`frequency`),
  CONSTRAINT `fk_reoccurrences_action` FOREIGN KEY (`action`) REFERENCES `actions` (`name`),
  CONSTRAINT `fk_reoccurrences_frequency` FOREIGN KEY (`frequency`) REFERENCES `frequencies` (`name`),
  CONSTRAINT `fk_reoccurrences_user` FOREIGN KEY (`username`) REFERENCES `users` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `days` (
  `reoccurrence` varchar(15) NOT NULL,
  `username` varchar(31) NOT NULL DEFAULT '',
  `day` tinyint(2) NOT NULL,
  PRIMARY KEY (`reoccurrence`,`username`,`day`),
  KEY `fk_days_reoccurrence2` (`username`),
  CONSTRAINT `fk_days_reoccurrence` FOREIGN KEY (`reoccurrence`) REFERENCES `reoccurrences` (`name`),
  CONSTRAINT `fk_days_reoccurrence2` FOREIGN KEY (`username`) REFERENCES `reoccurrences` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

注意,主要问题(我相信)是在这两个表之间。 还有其他几个相关的表格,但是如果我开始列出它们,那么这篇文章会变得很长。 如果您想查看完整的数据结构,可以在github上查看我的项目: https : //github.com/dallascaley/finance (我为我的github自述文件中的常识性/缺乏常识表示歉意,这不是供公众观看)

当我开始向这些表添加数据时,就会发生问题。 这是我的数据:

reoccurrences:

name, username, amount, action, frequency
Pay , dallas  , 2500  , credit, bi-weekly
Rent, dallas  , 1400  , debit , monthly

days:

reoccurrence, username, day
Rent        , dallas  , 1

忽略我没有一天或几天没有列出工资的事实。 由于某种原因,当表处于这种状态时,我无法从重现表中删除“付款”记录。 当我运行这个:

DELETE FROM reoccurrences WHERE `name` = 'Pay' AND `username` = 'dallas';

我收到以下错误:

Cannot delete or update a parent row: a foreign key constraint fails (`test`.`days`, CONSTRAINT `fk_days_reoccurrence2` FOREIGN KEY (`username`) REFERENCES `reoccurrences` (`username`))

如何更改表格结构以解决此问题?

您可能只需要在工作days解决约束,即可使用reoccurrences的组合键:

CREATE TABLE `days` (
  `reoccurrence` varchar(15) NOT NULL,
  `username` varchar(31) NOT NULL DEFAULT '',
  `day` tinyint(2) NOT NULL,
  PRIMARY KEY (`reoccurrence`,`username`,`day`),
  CONSTRAINT `fk_days_reoccurrence` FOREIGN KEY (`reoccurrence`,`username`) REFERENCES `reoccurrences` (`name`,`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

如您所见,我将fk_days_reoccurrence更改为一个组合键,并完全删除了fk_days_reoccurrence2 (键和外键引用)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM