如何将外键值设置为"NULL"?



删除表1中的主键时,如何将表2值中的外键设置为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

请使用以下语法和显式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只接受引用子句,当指定为单独的外键规范的一部分时。


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

最新更新