CREATE TABLE users(
USERID BIGINT AUTO_INCREMENT,
FNAME CHAR(50),
LNAME CHAR(50),
EMAIL CHAR (100),
PHONE CHAR (50),
PRIMARY KEY (USER_ID),
UNIQUE KEY EMAIL (EMAIL),
UNIQUE KEY PHONE (PHONE)
) ENGINE=InnoDB CHARSET=utf8mb4;
CREATE TABLE items(
ITEMS_ID BIGINT AUTO_INCREMENT,
USERID BIGINT,
ITEMS_TO BIGINT,
ITEMS_FROM BIGINT,
ACCEPTED_ITEMS BIGINT,
PRIMARY KEY (ITEMS_ID),
FOREIGN KEY (USERID) REFERENCES users(USERID),
FOREIGN KEY (ITEMS_TO) REFERENCES users(USERID),
FOREIGN KEY (ITEMS_FROM) REFERENCES users(USERID),
FOREIGN KEY (ACCEPTED_ITEMS) REFERENCES users(USERID)
) ENGINE=InnoDB CHARSET=utf8mb4;
我收到此错误
DBD :: mysql :: st执行失败:无法添加或更新子行: 外键约束失败(“ db701”。`items`,CONSTRAINT `items_ibfk_2`外键(`ITEMS_TO`)参考`users`(`USERID`))
运行此命令时
$ID = '1';
$NULL = 'NULL';
$ID2 = '2';
$ID3 = '1';
my $update = $DBH->prepare("UPDATE items SET ITEMS_TO =?, ITEMS_FROM =? WHERE USERID =? AND ITEMS_ID = ?");
$update->execute($ID, $NULL, $ID2, $ID3);
$update->finish();
它在没有ITEMS_FROM的情况下可以工作,我想将ITEMS_FROM设置为null。
这有效:
my $update = $DBH->prepare("UPDATE items SET ITEMS_TO =? WHERE USERID =? AND ITEMS_ID = ?");
$update->execute($ID, $ID2, $ID3);
$update->finish();
答案 0 :(得分:6)
您不应该在引号中加上NULL
。试图将ITEMS_TO
设置为文字字符串'NULL'
,而不是空值。然后,MySQL将尝试将其转换为BIGINT
;由于它看起来不像数字,它将被转换为0
。由于user_id = 0
表中没有users
,因此外键检查失败。
您应该使用Perl值undef
来表示SQL空值:
$NULL = undef;