本文介绍了仅当存在外键时才删除它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 MySQL 数据库中.
I'm on a MySQL database.
我正在这样做,但它不起作用.
I'm doing this, but it doesn't work.
ALTER TABLE `object` DROP FOREIGN KEY IF EXISTS `object_ibfk_1`;
我试图把这个 IF EXISTS 放在任何我能做的地方.如何在删除之前检查外键是否存在?
I've tried to put this IF EXISTS wherever I could. How can check if foreign key is exists before drop it?
推荐答案
如果你想删除外键(如果存在)并且不想使用过程你可以这样做(对于 MySQL) :
If you want to drop foreign key if it exists and do not want to use procedures you can do it this way (for MySQL) :
set @var=if((SELECT true FROM information_schema.TABLE_CONSTRAINTS WHERE
CONSTRAINT_SCHEMA = DATABASE() AND
TABLE_NAME = 'table_name' AND
CONSTRAINT_NAME = 'fk_name' AND
CONSTRAINT_TYPE = 'FOREIGN KEY') = true,'ALTER TABLE table_name
drop foreign key fk_name','select 1');
prepare stmt from @var;
execute stmt;
deallocate prepare stmt;
如果有外键,我们将alter table语句放入变量中,如果没有,我们放入一个虚拟语句.然后我们执行它.
If there is foreign key we put alter table statement in variable and if there isn't we put a dummy statement. And then we execute it.
这篇关于仅当存在外键时才删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!