【发布时间】:2020-04-20 10:48:27
【问题描述】:
我已阅读 MySQL 文档,但似乎无法找到解决此问题的方法。其他 StackOverFlow 问题并不能解决我的问题。
我有一个 MySQL 数据库,其中包含 3 个表,在此问题的范围内。 appointments、services 和 appointment_services,其中 appointments 和 services 具有通过 appointment_services 链接的多对多关系。
CREATE TABLE `appointment_services` (
`appointmentid` int(11) NOT NULL,
`serviceid` int(11) NOT NULL,
KEY `appointment_fk_idx` (`appointmentid`),
KEY `service_fk` (`serviceid`),
CONSTRAINT `appointment_fk` FOREIGN KEY (`appointmentid`) REFERENCES `appointments` (`appointmentid`),
CONSTRAINT `service_fk` FOREIGN KEY (`serviceid`) REFERENCES `services` (`serviceid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
CREATE TABLE `appointments` (
`appointmentid` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
PRIMARY KEY (`appointmentid`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8
CREATE TABLE `services` (
`serviceid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`description` mediumtext,
`parentid` int(11) DEFAULT NULL,
`session_duration` int(11) NOT NULL,
PRIMARY KEY (`serviceid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
services 已经有多行,包括带有serviceid = 1 的行。
当我使用事务尝试以下查询时,我收到一条错误消息,表明我违反了appointment_services 中的外键约束:
13:19:18 INSERT INTO `appointment_services` (appointmentid, serviceid) VALUES (1,1) Error Code: 1216. Cannot add or update a child row: a foreign key constraint fails 0.234 sec
BEGIN WORK;
INSERT INTO `appointments`
(appointmentid, date) VALUES (1, 2020/01/04);
INSERT INTO `appointment_services`
(appointmentid, serviceid) VALUES (1,1);
COMMIT;
我遇到了一些解决方案,说明我应该将约束设置为延迟,但是 MySQL 不支持。
【问题讨论】:
-
与其发明自己的模式语法,不如向我们展示一个简单的
SHOW CREATE TABLE YourTableName;用于所有 3 个表 -
另外,总是向我们展示完整的错误消息,如果你总结一下,你肯定会遗漏有人认为最重要的部分
-
发布的代码可以正常工作,没有错误,这意味着您的数据不是您认为的那样,或者错误来自其他地方可能是触发器。
-
@P.Salmon 我不这么认为,至少不像它发布的那样
标签: mysql concurrency transactions foreign-keys