我有2个innodb表,这里是SHOW CREATE TABLE查询:
| top_menu | CREATE TABLE `top_menu` (
`t_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`menu_photo` char(128) NOT NULL,
`title` char(64) NOT NULL,
`atdc_id` int(10) unsigned NOT NULL,
`menu_order` mediumint(8) unsigned NOT NULL,
PRIMARY KEY (`t_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 |
| attendance | CREATE TABLE `attendance` (
`atdc_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` char(128) NOT NULL,
`content` text,
`price` double NOT NULL,
`sale_percent` tinyint(3) unsigned NOT NULL,
`atdc_order` int(10) unsigned NOT NULL,
`s_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`atdc_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
做的结果,正常添加FOREIGN KEY是一个错误。
查询:ALTER TABLE top_menu ADD FOREIGN KEY (atdc_id) REFERENCES attendance(atdc_id);
错误:错误1452(23000):无法添加或更新子行:外键约束失败(database
。,CONSTRAINT #sql-a36a_5c109d2_ibfk_1
FOREIGN KEY(atdc_id
)参考attendance
(atdc_id
))
我该怎么办?它总是对我有用。
答案 0 :(得分:2)
似乎有些top_menu行的atdc_id在考勤表中不存在。
答案 1 :(得分:0)
补充@Alexey Smirnoff答案:
你什么时候添加外键?如果它来自还原脚本,请确保在执行此查询之前加载了attendance
表内容。或者将外键检查延迟到流程结束。
如果您想查找哪些行给您这个问题,请运行此查询:
Select a.*
from top_menu a
left join attendance b
on a.atdc_id = b.atdc_id
where b.atdc_id IS NULL;