当我尝试添加ON DELETE SET NULL时出现错误,但是当我在SQL(mysql服务器)中添加ON DELETE CASCADE时不出现错误

时间:2020-02-08 09:45:33

标签: mysql

我尝试在FOREIGN KEY上包括ON DELETE SET NULL约束,但出现错误1215。

    CREATE TABLE branch_supplier (
    -> branch_id INT,
    -> supplier_name VARCHAR(40),
    -> supply_type VARCHAR(40),
    -> PRIMARY KEY(branch_id, supplier_name),
    -> FOREIGN KEY(branch_id) REFERENCES branch(branch_id) ON DELETE SET NULL
    -> );
ERROR 1215 (HY000): Cannot add foreign key constraint

否则,如果我尝试包括ON DELETE CASCADE约束,则不会出现该错误。有人知道发生这种情况的原因吗?

    CREATE TABLE branch_supplier ( 
    -> branch_id INT,
    -> supplier_name VARCHAR(40), 
    -> supply_type VARCHAR(40), 
    -> PRIMARY KEY(branch_id, supplier_name), 
    -> FOREIGN KEY(branch_id) REFERENCES branch(branch_id) ON DELETE CASCADE 
    -> );
Query OK, 0 rows affected (0.26 sec)

1 个答案:

答案 0 :(得分:1)

这是因为您将branch_id字段作为主键,并且不允许使用Null值。

...
PRIMARY KEY(branch_id, supplier_name),
..