【问题标题】:My constraint foreign key is not working on my database我的约束外键在我的数据库上不起作用
【发布时间】:2020-02-17 08:41:59
【问题描述】:
create table students (StudentId int primary key not null);

create table records (
     RecordId int primary key not null,
     StudentId int not null,
     constraint fk foreign key(StudentId) references students(StudentId));

 insert into students values (201810696);
 Query OK, 1 row affected (0.120 sec)

 insert into records values (1011, 20181313);
 Query OK, 1 row affected (0.004 sec)

为什么它继续接受表学生中不存在的值?我已经在 phpmyadmin localhost 操作中将我的两个表上的存储引擎设置为 innoDb

顺便说一句,我正在使用最新版本的 wampp 并在 cmd 中编码

【问题讨论】:

  • 哪个数据库引擎?
  • 旧版本的 Innodb 不是默默地忽略 fk 的吗?
  • 我已将其设置为 innoDb
  • 我认为您应该仔细检查。使用SHOW CREATE TABLE students\GSHOW CREATE TABLE records\G,您将看到各自的ENGINE。
  • 另一种可能性:select @@foreign_key_checks; 确认您已启用 FK 的强制执行。如果启用,这将返回 1,否则返回 0

标签: mysql sql foreign-keys innodb


【解决方案1】:
create table students (StudentId int primary key not null);

create table records (RecordId int primary key not null, StudentId int not null, constraint fk 
foreign key(StudentId) references students(StudentId));

insert into records values(1, 1);

我在 mysql 5.6 中尝试过,插入失败:

Cannot add or update a child row: a foreign key constraint fails (`db_9_cd6353`.`records`, CONSTRAINT `fk` FOREIGN KEY (`StudentId`) REFERENCES `students` (`StudentId`))

您必须在主表中有您错过的相应数据。

【讨论】:

  • 是的,我已经在学生表中插入了一个值,但是一旦我在学生表中输入了不存在的值,记录表就会毫无错误地接受它。比如插入学生的价值观(201810696);查询正常,1 行受影响(0.120 秒)MariaDB [库]> 插入记录值(1011、20181313);查询正常,1 行受影响(0.004 秒)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-22
相关资源
最近更新 更多