我创建了 2 个测试表,试图链接 2 列。法典:
create table test (
id int primary key auto_increment
)ENGINE=InnoDB;
create table test2(
id int primary key auto_increment,
id2 int not null,
FOREIGN KEY (id2) REFERENCES test(id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB;
然后我在表格中插入 2 行:
insert into test (id) values(1);
insert into test2 (id,id2) values(1,1);
稍后我尝试从表"test"更新一行,据说它应该更新表"test2"中的一行,但它没有。
UPDATE test SET id=2 WHERE id=1;
SELECT * FROM test2;
查询结果:
+----+-----+
| id | id2 |
+----+-----+
| 1 | 1 |
+----+-----+
有什么建议吗?
您描述的行为与在 MySQL 中禁用外键检查一致。它还可能与使用不受支持、禁用或拼写错误的存储引擎一致。要检查存储引擎,请使用 . . .
show engines;
。并阅读 InnoDB 引擎的信息。如果您拼错了存储引擎的名称,MySQL将使用默认值。您的版本5.1.xx的默认存储引擎是MyISAM。MyISAM不强制执行外键约束。
要查看外键检查的当前设置,请使用 . . .
select @@FOREIGN_KEY_CHECKS;
为了演示您所看到的行为 . . .
create table test (
id int primary key auto_increment
)ENGINE=InnoDB;
create table test2(
id int primary key auto_increment,
id2 int not null,
FOREIGN KEY (id2) REFERENCES test(id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB;
insert into test (id) values(1);
insert into test2 (id,id2) values(1,1);
现在让我们关闭外键检查。
set foreign_key_checks = 0;
UPDATE test SET id=2 WHERE id=1;
SELECT * FROM test2;
身份证 ID2--1 1
没有错误或警告,但更新没有级联到"test2"。
现在让我们撤消我们所做的操作。 。
UPDATE test SET id=1 WHERE id=2;
。启用外键检查,然后再次运行该更新。
set foreign_key_checks = 1;
UPDATE test SET id=2 WHERE id=1;
SELECT * FROM test2;
身份证 ID2--1 2