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

时间:2017-10-20 14:57:00

标签: mysql foreign-keys database-normalization

我正在开展一个个人项目,这是我生命中第一次尝试建立一个规范化的数据库(至少是第一个规范化水平)。以下是我的问题所涉及的表格:

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

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

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`))

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

1 个答案:

答案 0 :(得分:2)

您可能只需要修复表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,包括密钥和外键引用。