我使用以下查询将外键添加到我的表中:
$query = "ALTER TABLE reserved ADD CONSTRAINT fk_test FOREIGN KEY (personel_num) REFERENCES members (personel_num) ON DELETE CASCADE ON UPDATE;";
if ($conn->query($query) === TRUE) {
return true;
} else {
echo $conn->error;
}
但我收到以下错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
personel_num
中的 members
是主键。
答案 0 :(得分:1)
试试这个
$query = "ALTER TABLE reserved ADD CONSTRAINT fk_test FOREIGN KEY (personel_num)
REFERENCES members members (personel_num) ON DELETE CASCADE ON UPDATE NO ACTION;";
答案 1 :(得分:1)
;
不是SQL语法的一部分,它只是一些工具用来表示SQL语句结束位置的终结符。
由于您以编程方式将SQL语句发送到数据库,因此不需要它。
此外,您应在更新时指定NO ACTION
:
$query = "ALTER TABLE reserved ADD CONSTRAINT fk_test " .
"FOREIGN KEY (personel_num) REFERENCES members (personel_num) " .
"ON DELETE CASCADE ON UPDATE NO ACTION";