简体   繁体   English

如何在不删除表的情况下更改外键引用 DELETE CASCADE

[英]How to alter Foreign Key reference ON DELETE CASCADE without dropping table

I have created database tables with foreign key reference ON UPDATE CASCADE ON DELETE RESTRICT .我创建了带有外键引用的数据库表ON UPDATE CASCADE ON DELETE RESTRICT However, I set my engine MyISAM so this reference does not work.但是,我设置了我的引擎 MyISAM,所以这个引用不起作用。 The primary key is being deleted even if it is used elsewhere as foreign key.即使主键在其他地方用作外键,也会被删除。 How can I fix this issue?我该如何解决这个问题? I tried to alter table engine to InnoDB, but even if it is set to InnoDB the foreign references does not work.我试图将表引擎更改为 InnoDB,但即使将其设置为 InnoDB,外部引用也不起作用。 Moreover, I tried to drop one empty table with foreign key reference and engine MyISAM.此外,我试图删除一个带有外键引用和引擎 MyISAM 的空表。 Then I tried to add that table, but it does not add.然后我尝试添加该表,但它没有添加。 Most probably when I drop table foreign references remain somewhere in schemas.很可能当我删除表时,外部引用仍保留在模式中的某处。

My query to create table.我的查询创建表。

CREATE TABLE IF NOT EXISTS `products` (
    `productid` int(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `productname` varchar(255) NOT NULL,
    `productcode` varchar(255) NOT NULL,
    `producttype` varchar(255) NULL
) 
ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `sales` (
    `salesid` int(10) NOT NULL AUTO_INCREMENT PRIMARY KEY
    `productid` int(10) NOT NULL,
    `quantity` int(10) NOT NULL,
    `price` int(10) NOT NULL,
    `date` datetime NOT NULL,
    CONSTRAINT `fk_sales_productid` 
    FOREIGN KEY (productid) 
    REFERENCES products(productid) ON UPDATE CASCADE ON DELETE RESTRICT
) 
ENGINE=MyISAM DEFAULT CHARSET=utf8;

These 2 tables were created with this query as MyISAM.这 2 个表是使用此查询作为 MyISAM 创建的。 They have data on it which i need.他们有我需要的数据。 I run this query to change engine to InnoDB as reference on delete cascade were not working in MyISAM.我运行此查询以将引擎更改为 InnoDB,因为删除级联的参考在 MyISAM 中不起作用。 'ALTER TABLE products ENGINE=InnoDB;' 'ALTER TABLE sales ENGINE=InnoDB;' But after making them InnoDB, the reference still does not work when I delete product, related productid in sales table becomes NULL.但是制作InnoDB后,删除产品时引用仍然不起作用,销售表中的相关产品ID变为NULL。

As per P.Salmon's demo queries seems valid.根据 P.Salmon 的演示查询似乎有效。 You probably missing something in FK references.您可能在 FK 参考资料中遗漏了一些东西。 I suggest you to export 2 tables, the examine it in editor, especially FK references part and make sure engine is InnoDB as it has row-level locking and has what is called referential integrity that involves supporting foreign keys and relationship constraints.我建议您导出 2 个表,在编辑器中检查它,尤其是 FK 引用部分并确保引擎是 InnoDB,因为它具有行级锁定并且具有涉及支持外键和关系约束的所谓的参照完整性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM