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

What is wrong with my mysql foreign key constraints?

我正在做一个个人项目,这是我有生以来第一次真正尝试制作一个规范化的数据库(至少达到规范化的第一个级别)。以下是涉及我的问题的 table:

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;

请注意,主要问题(我相信)在这两个 table 之间。还有其他几个相关的 table,但如果我开始列出它们,这个 post 会变得很长。如果你想查看完整的数据结构,你可以在 github 上查看我的项目:https://github.com/dallascaley/finance(我对我的 github 自述文件中的 profanity/lack 常识表示歉意,它不适合 public 查看)

当我开始向这些 table 添加数据时出现问题。这是我的数据:

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 的事实。由于某些原因,当 table 处于此状态时,我无法从重现 table 中删除付款记录。当我 运行 这个:

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

如何更改我的 table 结构来解决这个问题?

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