mysql8.0.16,innodb。
我有两个表,定义如下:
CREATE TABLE `t1` (
`t1_id` int(11) NOT NULL AUTO_INCREMENT,
`t2_id` int(11) DEFAULT NULL,
PRIMARY KEY (`t1_id`),
KEY `FKi35qhb7o9h73w2et7geh4xwvt` (`t2_id`),
CONSTRAINT `FKi35qhb7o9h73w2et7geh4xwvt` FOREIGN KEY (`t2_id`) REFERENCES `t2` (`t2_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `t2` (
`t2_id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`t2_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
我不小心发现:表t1中有一些记录,表t2中没有记录t2_id的值。如下:
mysql> select t1_id, t2_id from t1 where t2_id=11624;
+----------+-----------+
| t1_id | t2_id |
+----------+-----------+
| 6 | 11624 |
mysql> select t2_id from t2 where t2_id=11624;
Empty set (0.00 sec)
外键不起作用?因此,我尝试插入一条新记录:
mysql> select * from t2 where t2_id=12000;
Empty set (0.00 sec)
mysql> insert into t1(t2_id) value(12000);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`t1`, CONSTRAINT `FKi35qhb7o9h73w2et7geh4xwvt` FOREIGN KEY (`t2_id`) REFERENCES `t2` (`t2_id`))
发生了什么事?为什么表t1中有这样的记录(6,11624)? 我不知道。
请帮助我,谢谢!