简体   繁体   English

mysql删除和外键约束

[英]mysql delete and foreign key constraint

I'm deleting selected rows from both table in MYSQL, the two tables have foreign keys. 我在MYSQL中删除了两个表中的选定行,这两个表都有外键。

DELETE d,b
  FROM A as b
  INNER JOIN B as d on b.bid=d.bid WHERE b.name LIKE '%xxxx%';

MYSQL complains about foreign keys even though I'm trying to delete from both tables: MYSQL抱怨外键,即使我试图从两个表中删除:

Error: Cannot delete or update a parent row: a foreign key constraint
fails (`yyy/d`, CONSTRAINT `fk_d_bid` FOREIGN KEY (`bid`) REFERENCES 
`b` (`bid`) ON DELETE NO ACTION ON UPDATE NO ACTION)

what's the best solution here to delete from both table? 从这两个表中删除的最佳解决方案是什么?

Change this constraint to use ON DELETE CASCADE -- which means that if a row is deleted, then any "child" rows will be automatically deleted as well. 更改此约束以使用ON DELETE CASCADE - 这意味着如果删除行,则也会自动删除任何“子”行。

Of course take good care of using CASCADE -- only use it when necessary. 当然要好好使用CASCADE - 只在必要时使用它。 If you're overzealous with it, and accidentally do a well-placed DELETE, it might end up deleting half of your database. 如果你对它过于热心,并且不小心做了一个位置很好的DELETE,它最终可能会删除你数据库的一半。 :) :)

See documentation on foreign key constraints . 请参阅有关外键约束的文档

I think I see what you're trying to do 我想我明白你在做什么

If you can't change the table structure, then you could use 2 statements, the first with a sub-select 如果您无法更改表结构,那么您可以使用2个语句,第一个使用子选择

delete from B where bid IN (select bid from A where name like '%xxxx%'); 从B中删除出价IN(从A中选择出价,其中名称为'%xxxx%');

delete from A where name like '%xxxx%'; 从A中删除名称'%xxxx%';

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

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