【问题标题】:How to set the foreign key value as 'NULL'?如何将外键值设置为“NULL”?
【发布时间】:2014-01-06 11:18:27
【问题描述】:

table1的主键被删除时,如何设置table2的外键为NULL? 我创建了 2 个表 Itemorder_item

Item(item_no(primary key),qty);  
order_item(item_no(foreign key ),order_no);   

我已经创建了表order_item

 create table order_item(  
 item_no int references item on  delete set NULL,  
  order_no  int);  

然后我在Item 表中插入了 5 个值。 现在,如果我删除项目表中的item_no = 4,它会在Item 表中被删除,但item_no 的值在order_item 表中未设置为NULL

【问题讨论】:

    标签: mysql null foreign-keys


    【解决方案1】:

    请使用以下语法并使用显式 CONSTRAINT [name] FOREIGN KEY ... 子句:

    CREATE TABLE order_item1(
      item_no int,  
      order_no  int,
      constraint foreign key (item_no) references item( item_no ) on  delete set NULL 
    );
    

    或将外键显式添加到现有表中:

    ALTER TABLE order_item1
    ADD constraint foreign key (item_no) references item( item_no ) on  delete set NULL ;
    

    请看一下这个简单的测试用例:http://www.sqlfiddle.com/#!2/3dddf/1
    内联引用子句不起作用。

    文档中描述了这种奇怪行为的原因,请查看此链接:
    http://dev.mysql.com/doc/refman/5.7/en/create-table.html

    MySQL 不识别或支持“内联引用规范”(如 SQL 标准中所定义),其中引用被定义为列规范的一部分。 MySQL 仅在指定为单独的 FOREIGN KEY 规范的一部分时才接受 REFERENCES 子句。


    内联(inline=列定义旁边)引用规范由 MySql 解析,但 MySql 只是忽略它们。

    【讨论】:

    • 你为什么使用另一个表?
    • 我在演示中使用了两个表order_itemorder_item1,仅使用一个测试用例来展示它们的不同之处(运行delete 后的结果)。如果我要使用相同的表名,则需要两个测试用例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2012-03-30
    • 2017-01-06
    • 1970-01-01
    相关资源
    最近更新 更多